简体   繁体   中英

Javascript Object Literal - calling

What's the way of calling the property within the method of the specific object - here's an example:

var myObject ={
    firstProperty : 0,
    secondProperty : 0,
    myMethod : function(){
         // this is where I'm not quite sure
          $(this).firstProperty = 1;
    }
}

I'm sure $(this).firstProperty = 1 is wrong - but how would I call the property within the method of the object (self, this etc.)?

The best way to do it is to avoid using this altogether:

var myObject ={
    firstProperty : 0,
    secondProperty : 0,
    myMethod : function(){
          myObject.firstProperty = 1;
    }
}

The reason is that the meaning of this changes depending on the context. For example, with the code in your question, what happens when you do document.getElementById('somelement').onclick = myObject.myMethod ? The answer is that firstProperty will instead be set on somelement . The same goes for this:

var f = myObject.myMethod;
f(); // firstProperty is now set on the window object!
console.log(window.firstProperty); // Logs 1 to the console

So be warned:)

What's the way of calling the property within the method of the specific object

very confusing....

I think another way to ask this is

How do I reference a property of an object, from within one of its methods?

If this is a accurate way to explain what you are looking for then...

In this case this will reference myObject .

so this.firstProperty should work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM