Javascript闭包和'这个'

我有一个问题,我创建的对象看起来像这样:


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'我做错了什么?


繁花不似锦
浏览 345回答 3
3回答

一只名叫tom的猫

当函数被调用时,“this”指的是行。如果你想拥有这个对象,你可以这样做:]AddChildRowEvents: function(row, p2) {&nbsp; &nbsp; var theObj = this;&nbsp; &nbsp; if(document.attachEvent) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;row.attachEvent('onclick', function(){theObj.DoSomething();});&nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;row.addEventListener('click', function(){theObj.DoSomething();}, false);&nbsp; &nbsp; }},调用该函数时,它可以访问定义函数时在范围内的变量theobj。

慕村225694

this总是指内部函数,如果你有嵌套函数,你必须创建另一个变量并指向它this。var myObject = {&nbsp; &nbsp; AddChildRowEvents: function(row, p2) {&nbsp; &nbsp; &nbsp; &nbsp; var that = this;&nbsp; &nbsp; &nbsp; &nbsp; if(document.attachEvent) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; row.attachEvent('onclick', function(){that.DoSomething();});&nbsp; &nbsp; &nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; row.addEventListener('click', function(){that.DoSomething();}, false);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }}

宝慕林4294392

这是闭包的常见问题。要解决它尝试这样的事情:var myObject = {&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; AddChildRowEvents: function(row, p2) {&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; var self = this;&nbsp; &nbsp; &nbsp; &nbsp; if(document.attachEvent) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;row.attachEvent('onclick', function(){this.DoSomething(self);});&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;row.addEventListener('click', function(){this.DoSomething(self);}, false);&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; },&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; DoSomething: function(self) {&nbsp; &nbsp; &nbsp; &nbsp;&nbsp; &nbsp; &nbsp; &nbsp; self.SomethingElse();&nbsp;&nbsp; &nbsp; }}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript