组合类和事件监听器:`this`关键字
Combining Classes and Event Listeners: `this` keyword
我很难回答我的问题,我认为这只是因为"类"、"这个"和其他类似的术语太通用了,无法有效地在谷歌上搜索。
考虑以下代码:
function product (name) {
var _productName;
this.getProductName = function() {
return this._productName;
};
this.alertProductName = function() {
// This errors because `this` is a reference to the HTML <input> tag and not the class
alert(this.getProductName());
}
this._productName = name;
var $productButton = $('<input type="button" value="What is my name?" />');
$productButton.on('click', this.alertProductName);
$('body').append($productButton);
}
var widget = new product('Widget');
widget.alertProductName();
一旦product::alertProductName被调用为事件的回调,jQuery(或者可能是Javascript本身)正在重置this关键字所指向的内容。我找不到任何其他方法从用作回调的函数中访问此类的特定实例。它看起来像Javascript曾经有arguments.callee,但这已经被弃用了。
有人知道我如何以这种方式访问类的特定实例吗?如果没有,有没有更好的方法来写这篇文章,这样我一开始就不会有这个问题?
由于方法alertProductName
由事件处理程序调用,因此默认情况下,事件处理程序方法中的this
指触发事件的dom元素。
由于您使用的是构造函数,我的首选解决方案是使用$.proxy()-Function.bind()将自定义执行上下文传递给alertProductName
方法;9支持
function product(name) {
var _productName;
this.getProductName = function () {
return this._productName;
};
this.alertProductName = function () {
// This errors because `this` is a reference to the HTML <input> tag and not the class
alert(this.getProductName());
}
this._productName = name;
var $productButton = $('<input type="button" value="What is my name?" />');
$productButton.on('click', $.proxy(this.alertProductName, this));//here use $.proxy()
$('body').append($productButton);
}
var widget = new product('Widget');
widget.alertProductName();
演示:Fiddle
另一个解决方案是使用闭包变量来引用小部件元素,例如:fiddle-如果您计划确保构造函数的原型函数,这将不起作用
这不是你想象的那样。
这很好地回答了问题
";这个";关键词工作?
相关文章:
- JavaScript 中的嵌套函数和 “this” 关键字
- Javascript 对象和 this 关键字
- 将“this”关键字发送到对象中
- 如何使用“this”关键字来调用a
- 组合类和事件监听器:`this`关键字
- 将this关键字与selectedIndex一起使用的优势
- 在forEach中调用类函数:Javascript如何处理“this”关键字
- 使用“this”关键字响应类行为
- Javascript 'this' 关键字 在嵌套函数中
- 事件处理函数不适用于“this”关键字
- (无效)如何在 JSON 中使用“this”关键字
- JavaScript Promise 和 this 关键字
- 如何在 html 中使用“this”关键字在对象上调用方法
- Javascript中“this”关键字的目的是什么?
- 处理 jQuery 事件时在 JavaScript 类中覆盖的 'this' 关键字
- PHP 相当于 JavaScript “this” 关键字,特别是在对象中
- 嵌套函数中“this”关键字的范围
- 在我的命名空间JavaScript中使用this关键字
- JavaScript 中的 'this' 关键字
- Javascript [this] 关键字绑定与 new