wizztjh
wizztjh

Reputation: 7041

access object name within the object with this

in i want to alert the 'image' which is the object name, how can i access with this ?

Objectswitch={
    'image':
    {
        addCount:function(){
            alert('count');
        },
        addCountandCreate:function(){
            this.addCount();
            alert(this);
        }
    }
}

Upvotes: 1

Views: 229

Answers (2)

Mark Bessey
Mark Bessey

Reputation: 19782

You'll need to add the name as a property of the object:

var imageObj = {
  name: "image",
  addCount:function(){
    alert('count');
  },
  addCountandCreate:function(){
     this.addCount();
     alert(this.name);
  }
}

you can then reference that object from within another, of course:

ObjectSwitch = {
  "image": imageObj
}

Upvotes: 1

user578895
user578895

Reputation:

Sorry, you can't with that structure. this refers to the object: {addCount:, addCountandCreate:} and JS has no way to say this.parentObject (which doesn't make sense anyway since an object can have multiple references)

Upvotes: 3

Related Questions