在javascript中的函数内访问实例变量? [英] Access instance variable inside a function in javascript?

查看:86
本文介绍了在javascript中的函数内访问实例变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何以最简单的方式访问函数内的实例变量?

How can I in the easiest way access an instance variable inside a function?

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();

请注意,我可以设置 button.onclick = this.handler; 。这只是一个例子。主要问题是如何在该函数中访问 this.handler

Note that I can set button.onclick = this.handler;. This is just an example. The main question is how I can access this.handler inside that function?

我还可以定义一个新变量 var handler = this.handler 访问 this.handler 。但如果更改处理程序 this.handler 也会更改?

I can also define a new variable var handler = this.handlerto access this.handler. But If a change handlerwill this.handler also be changes?

推荐答案

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();

如果将其赋值给外部函数范围内的var,则将其传递给内部函数功能范围链。在你的内部函数中,引用this引用内部函数,引用你赋给它的变量,在我们的例子中,that,引用回那个对象。

If you assign this to a var within the scope of the outer function, it is passed to the inner functions scope chain. Within your inner function referencing this refers to the inner function, referencing the variable you assigned this, in our case "that", refers back to that object.

这篇关于在javascript中的函数内访问实例变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆