【发布时间】:2013-12-23 06:41:12
【问题描述】:
我很难回答我的问题,我认为这仅仅是因为“类”和“这个”以及其他此类术语对于有效的谷歌搜索来说过于笼统。
考虑以下代码:
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();
jQuery(或者可能是 Javascript 本身)正在重置 this 关键字指向的内容,一旦 product::alertProductName 被调用作为事件的回调。我找不到任何其他方法来从用作回调的函数中访问此类的特定 instance。看起来 Javascript 曾经有 arguments.callee 但已被弃用。
有谁知道我如何以这种方式访问类的特定实例?如果没有,有没有更好的方法来写这个,这样我一开始就没有这个问题?
【问题讨论】:
-
典型答案:在更高的范围内缓存
this,例如var self = this,然后使用self代替this。 -
或使用$.proxy()
-
远离
$productButton之类的变量,这样您就可以在PHP 中使用JavaScript,只需使用var productButton。$('body')、$.ajax()等都可以。它将节省潜在的未来头痛。只是评论。 -
@PHPglue:这是一个约定 stackoverflow.com/questions/205853/…。我没有看到任何混乱。
-
@PHPglue:在 PHP 双引号字符串中使用 jQuery $ 语法本身听起来像是一种非常糟糕的做法。我尝试使用“字符串”。 $var 。无论如何,PHP 中的 string' 而不是 "{$var}"。无论哪种方式,我都不会将 PHP 和 JS 结合起来,这是一个问题。
标签: javascript jquery oop functional-programming jquery-events