[英]Access an instance variable inside an anonymous function inside prototype method
This is actually a follow up question to my previous question, Access instance variable inside a function in javascript?这实际上是我上一个问题的后续问题, Access instance variable inside a function in javascript? . .
I want to access an instance variable inside an anonymous function inside prototype method.我想在原型方法中访问匿名 function 中的实例变量。
function MyObject(){
//Instance variables
this.handler;
}
//Methods
MyObject.prototype.enableHandler = function(){
var button = document.getElementById('button');
button.onclick = function(){
this.handler();//Is not working
}
}
var myObject = new MyObject();
myObject.handler = function(){
alert('Hello World!');
}
myObject.enableHandler();
JSFiddle http://jsfiddle.net/3cmvZ/ JSFiddle http://jsfiddle.net/3cmvZ/
The example above was just to clarify how I can access an instance variable inside an anonymous function inside a prototype method.上面的示例只是为了阐明如何在原型方法中访问匿名 function 中的实例变量。 I already know that button.onclick = this.handler
works.我已经知道button.onclick = this.handler
有效。
The problem is not that the anonymous function is in the prototype, but rather that it is an event handler (which is not invoked as a method).问题不在于匿名 function 在原型中,而在于它是一个事件处理程序(不作为方法调用)。
The problem is that in your onclick handler, the this
keywords is bound to the windows
object, not to the myObject
instance that the prototype is set on.问题是在您的 onclick 处理程序中, this
关键字绑定到windows
object,而不是设置原型的myObject
实例。 You can store the object in a that
variable and create a closure:您可以将 object 存储在that
变量中并创建一个闭包:
function MyObject(){
//Instance variables
this.handler;
}
//Methods
MyObject.prototype.enableHandler = function(){
var button = document.getElementById('button');
var that = this;
button.onclick = function(){
that.handler();//Should be working
}
}
var myObject = new MyObject();
myObject.handler = function(){
alert('Hello World!');
}
myObject.enableHandler();
this.handler
is not in the same scope. this.handler
不在同一个 scope 中。 You need to declare it as:您需要将其声明为:
MyObject.prototype.enableHandler = function() {
var button = document.getElementById("button");
button.onclick = this.handler;
}
As you are simply calling the event directly, you need not wrap it in another function.由于您只是直接调用事件,因此无需将其包装在另一个 function 中。
Update based on your comment:根据您的评论更新:
MyObject.prototype.enableHandler = function() {
var button = document.getElementById("button");
var $this = this;
button.onclick = function() {
$this.handler();
}
}
You need to make a local variable that is in the same scope as the anonymous function.您需要创建一个与匿名 function 位于同一 scope 中的局部变量。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.