Javascript Object Literal - 调用

时间:2011-07-21 19:45:37

标签: javascript object literals

在特定对象的方法中调用属性的方式是什么 - 这是一个例子:

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

我确定 $(this).firstProperty = 1 是错误的 - 但是如何在对象的方法中调用属性(self,this等)?

2 个答案:

答案 0 :(得分:3)

最好的方法是避免完全使用this

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

原因是this的含义根据上下文而改变。例如,根据您的问题中的代码,当您执行document.getElementById('somelement').onclick = myObject.myMethod时会发生什么?答案是firstProperty将设置在somelement上。同样如此:

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

所以请注意:)

答案 1 :(得分:2)

在特定对象
的方法中调用属性的方式是什么

非常混乱....

我认为另一种问题是

如何从其中一个方法中引用对象的属性?

如果这是解释您所寻找内容的准确方法,那么......

在这种情况下,this会引用myObject

所以this.firstProperty应该有用。