我有一个问题,我创建的对象看起来像这样:
var myObject = { AddChildRowEvents: function(row, p2) { if(document.attachEvent) { row.attachEvent('onclick', function(){this.DoSomething();}); } else { row.addEventListener('click', function(){this.DoSomething();}, false); } }, DoSomething: function() { this.SomethingElse(); //<-- Error here, object 'this' does not support this method. } }
问题是当我进入'DoSomething'函数时,'this'不会引用'myObject'我做错了什么?
当函数被调用时,"this"指的是行.如果你想拥有这个对象,你可以这样做:]
AddChildRowEvents: function(row, p2) { var theObj = this; if(document.attachEvent) { row.attachEvent('onclick', function(){theObj.DoSomething();}); } else { row.addEventListener('click', function(){theObj.DoSomething();}, false); } },
调用该函数时,它可以访问定义函数时在范围内的变量theobj.
this
总是指内部函数,如果你有嵌套函数,你必须创建另一个变量并指向它this
.
var myObject = { AddChildRowEvents: function(row, p2) { var that = this; if(document.attachEvent) { row.attachEvent('onclick', function(){that.DoSomething();}); } else { row.addEventListener('click', function(){that.DoSomething();}, false); } } }