0

我有一个 javascript 对象,我希望它能够处理一些交互功能。以简单的方式描述场景有点棘手,所以希望它不会在这里完全失控。

我的对象看起来像

myobject = function() {
    this.initialize = function() {
        // HERE this = the myobject instance
        var test = document.createElement('div');
        test.onmousedown = this.mousedown;
    }
    this.mousedown = function(e) {
        // HERE this = the calling div-element
    }
}

所以我的问题基本上是在被调用时this不会是myobject实例this.mousedown(e),而是调用者(如果术语正确?)在这种情况下,它是我创建的 div 并放入test上面调用的变量中。

我想访问正在运行该方法的实例(因为我相信这是mousedown我创建的方法)。

到目前为止,我已经尝试了一些想法:

  • 在包含对象的对象上创建一个data-属性并对其进行操作。divthis
  • 将 this 指针作为参数与eto一起发送this.mousedown(e)

我现在能想到的就这些了,希望有道理。

4

2 回答 2

4

您可以在第一次实例化对象时创建一个副本:

var myobject = function() {
    var self = this;    
    this.initialize() {
        // HERE this = the myobject instance
        var test = document.createElement('div');
        test.onmousedown = this.mousedown;
    }
    this.mousedown(e) {
        // HERE this = the calling div-element
        // use self instead of this
    }
}
于 2013-04-18T21:57:12.700 回答
0

最简单的解决方案是制作一个您在回调中引用的“自我”变量:

myobject = funciton() {
    var self = this;
    this.initialize() {
        //use self to refer to myobject
        self.mousedown(e);
    }
    this.mousedown(e) {

    }
}
于 2013-04-18T21:56:29.720 回答