我怎样才能以最简单的方式访问函数内的实例变量?
function MyObject(){
//Instance variables
this.handler;
//Methods
this.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();
Run Code Online (Sandbox Code Playgroud)
请注意,我可以设置button.onclick = this.handler;.这只是一个例子.主要问题是我如何访问this.handler该函数内部?
我还可以定义一个新的变量var handler = this.handler来访问this.handler.但如果变化handler也会this.handler发生变化?
Kev*_*sox 10
function MyObject(){
//Instance variables
this.handler;
var that = this; //notice change
//Methods
this.enableHandler = function(){
var button = document.getElementById('button');
button.onclick = function(){
that.handler();//Is not working notice the change
}
}
}
var myObject = new MyObject();
myObject.handler = function(){
alert('Hello World!');
}
myObject.enableHandler();
Run Code Online (Sandbox Code Playgroud)
如果将此值赋给外部函数范围内的var,则将其传递给内部函数作用域链.在你的内部函数中,引用this引用内部函数,引用你赋予它的变量,在我们的例子中,"that",引用回那个对象.