gpt4 book ai didi

javascript - 在 JavaScript 事件处理程序中处理对象函数

转载 作者:行者123 更新时间:2023-11-30 10:44:26 24 4
gpt4 key购买 nike

假设我有一个这样的 JavaScript 类:

Foo.prototype = {
init: function() {
$(document).keydown(function(event) {
this.onKeyDown(event);
});
}

onKeyDown: function(event) {
alert("bar");
}
}

myObj = new Foo();
myObj.init();

此代码将不起作用,因为在

$(document).keydown(function(event) {
this.onKeyDown(event);
});

“this”当然是未知的,并且不指向该对象。我怎样才能解决 Foo 类的 onkeydown 方法?

我不想将“this”与“myObj”(对象的名称)交换,因为我可能还想将该类用于其他对象。

感谢您的帮助!

最佳答案

将其存储在变量中...

Foo.prototype = {
init: function() {
var self = this
$(document).keydown(function(event) {
self.onKeyDown(event);
});
}
}

或者使用 jQuery.proxy 返回一个带有 this 值绑定(bind)的函数...

Foo.prototype = {
init: function() {
$(document).keydown( $.proxy(function(event) {
this.onKeyDown(event);
}, this) );
}
}

或者您可以使用 Function.prototype.bind,但您需要为旧版浏览器打补丁。

Foo.prototype = {
init: function() {
$(document).keydown( (function(event) {
this.onKeyDown(event);
}).bind(this) );
}
}

关于javascript - 在 JavaScript 事件处理程序中处理对象函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9253978/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com