开发者

Javascript Object Literal - calling

开发者 https://www.devze.com 2023-03-21 22:00 出处:网络
What\'s the way of calling the property within the method of the specific object - here\'s an example:

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号