gpt4 book ai didi

javascript - 如何使用 JavaScript OOP 在附加的事件处理程序中引用 'real' this?

转载 作者:行者123 更新时间:2023-11-30 00:28:39 27 4
gpt4 key购买 nike

如何使用 JavaScript OOP 在附加的事件处理程序中引用“真实的”this?

使用局部变量“anyVariable”引用实例是最佳做法吗?

var myClass = (function () {
function myClass(gridId) {
$(function () {
// misc init code replaced here
this.initKeyboard();
});

}

myClass.prototype.initKeyboard = function () {
var anyVariable = this; // keyword 'this' is clearly referring here to the instance
$(document).keyup(function (e) {
// I would like to refer here to the instance.
// However it seems that the keyword 'this' refers here to the function (?)
// Is is the best practice here to refer to the instance by using the local variable 'anyVariable'?
anyVariable.myMember(...); //???
}
});
};

最佳答案

通常的变量名称是 selfthat_this(更多详细信息请参见 question),但是,是的,这是当上下文改变时保持所需的 this 值的通常方法

关于javascript - 如何使用 JavaScript OOP 在附加的事件处理程序中引用 'real' this?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30459434/

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