我有一个 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.mousedown(e)
时 this
不会是 myobject
实例,而是是调用者(如果术语正确?)在本例中,它是我创建并放入上面名为 test
的变量中的 div。
我想访问正在运行该方法的实例(因为我相信这是我创建的 mousedown
方法)。
到目前为止,我已经尝试过一些想法:
- 在包含
this
对象的div
上创建一个data-
属性并对其进行操作。 - 将 this 指针作为参数与
e
一起发送到this.mousedown(e)
我现在能想到的就是这些,希望它有意义。
最佳答案
您可以在第一次实例化对象时创建一个副本:
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
}
}
关于javascript - javascript 中的困惑、this 指针和事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16093758/