我已经声明了一个 JavaScript 对象:
function A(name){
this.name=name
}
A.prototype.test=function(){
console.log(this.name);
};
作为一个简单的示例,我设置了一个按钮,如果单击该按钮,应将变量输出到本地控制台日志:
<button id='test'>test</button>
脚本:
var t=new A('hello');
$('#test').click(t.test);
当我点击我想要的按钮this.name
显示(在本例中为“hello”),而是 this
指的是单击的按钮,而不是我创建的对象。
这当然是一个调试脚本。在现实生活中,我将一个函数绑定(bind)到 window.resize 事件,该事件将在调整大小时重新构建窗口。
有一个JSFiddle这说明了问题。
对此我有一个解决方案,即在对象的构造函数中声明调整大小(或单击函数)并使用 this
的替代名称。 ,就像这样( Here's the JSFiddle ):
function A(name){
this.name=name
var self=this;
$("#test").click(function(){
console.log(self.name);
});
}
但我宁愿使用原型(prototype)并将函数绑定(bind)到对象的构造函数中。我如何使用原型(prototype)来做到这一点?
最佳答案
您可以使用bind
,这将提前设置 this
的值:
var t=new A('hello');
$('#test').click(t.test.bind(t));
关于javascript - jQuery 覆盖原型(prototype)中的 'this',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33758753/