简体   繁体   English

访问 javascript 中的 function 内的实例变量?

[英]Access instance variable inside a function in javascript?

How can I in the easiest way access an instance variable inside a function?如何以最简单的方式访问 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();

Note that I can set button.onclick = this.handler;请注意,我可以设置button.onclick = this.handler; . . This is just an example.这只是一个例子。 The main question is how I can access this.handler inside that function?主要问题是如何在 function 中访问this.handler

I can also define a new variable var handler = this.handler to access this.handler .我还可以定义一个新变量var handler = this.handler来访问this.handler But If a change handler will this.handler also be changes?但是如果一个更改handlerthis.handler也会更改吗?

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

If you assign this to a var within the scope of the outer function, it is passed to the inner functions scope chain.如果将其分配给外部 function 的 scope 内的 var,则它将传递给内部函数 scope 链。 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.在你的内部 function 中引用 this 是指内部 function,引用你分配的变量,在我们的例子中是“那个”,指回那个 object。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM