Lis*_*ish 2 javascript jquery scope bind this
我使用bind来改变'this'的范围,这样我就可以在click函数中使用'this'来引用我的generateContent函数.不幸的是,这意味着this.id不再起作用,因为'this'的范围已经改变.
在这种情况下,获取单击按钮的id的最佳方法是什么:
function help( doc ) {
buttons: function() {
$('.add-btn').click( function() {
this.generateContent( this.id ) );
}.bind(this));
},
generateContent: function ( id ){
}
}
// This function binds a function to an object's scope.
Function.prototype.bind = function(scope) {
var _function = this;
return function() {
return _function.apply(scope, arguments);
}
}
Run Code Online (Sandbox Code Playgroud)
你没有标记jQuery,但你的代码嘎嘎叫jQuery,所以我假设jQuery.
jQuery提供event.currentTarget:
$('.add-btn').click( function(e) {
this.generateContent( e.currentTarget.id ) ;
}.bind(this));
Run Code Online (Sandbox Code Playgroud)
Btw Function.prototype.bind本机存在,您不希望在本机版本可用的情况下覆盖它.jQuery也提供了$.proxy,所以你无论如何都不需要它.