2011-07-04 34 views
2

这实际上是对我之前的问题Access instance variable inside a function in javascript?的后续问题。访问原型方法内的匿名函数内的实例变量

我想访问原型方法内的匿名函数内的实例变量。上述

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/

的例子只是为了阐明如何可以访问一个实例变量的匿名函数内部的原型方法内。我已经知道button.onclick = this.handler的作品。

回答

2

this.handler不在同一范围内。您需要将其声明为:

MyObject.prototype.enableHandler = function() { 
    var button = document.getElementById("button"); 
    button.onclick = this.handler; 
} 

由于您只是直接调用该事件,因此无需将其包装在另一个函数中。

更新根据您的评论:

MyObject.prototype.enableHandler = function() { 
    var button = document.getElementById("button"); 
    var $this = this; 

    button.onclick = function() { 
     $this.handler(); 
    } 
} 

你需要做一个局部变量是在同一范围内的匿名函数。

+0

忘了提及的例子只是为了澄清我如何可以访问一个实例变量的匿名函数内部的原型方法中。我已经知道'button.onclick = this.handler'作品 – einstein

+0

@ Woho87 - 查看更新。 –

+0

如果我更改'$ this.handler',this.handler是否也会被更改?' – einstein

3

问题不在于匿名函数在原型中,而在于它是一个事件处理程序(不作为方法调用)。

问题是,在您的onclick处理程序中,this关键字绑定到windows对象,而不是绑定到原型设置的myObject实例。你可以存储在一个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(); 
+0

如果我改变'that.handler'这个.handler也会被改变吗? – einstein

+0

只要'that'和'this'是同一个对象,那么是的。 –