无法在匿名函数处理程序中从fx2访问fx1?
var MyComponent = function () {
//my constructor
}
MyComponent.prototype.fx1 = function() { //code }
MyComponent.prototype.fx2 = function() {
var btn1 = document.getElementById('Button1')
btn1.onclick = function() {
//issue is here
//trying to call fx1 from here but can't access it.
this.fx1(); //doesn't work.
}
}
答案 0 :(得分:5)
由于this
绑定到onclick
处理程序中的按钮,因此您无法使用它来访问MyComponent
实例。但您可以将引用保存在另一个变量中,然后可以使用该变量:
MyComponent.prototype.fx2 = function() {
// save reference to the instance
var self = this;
var btn1 = document.getElementById('Button1')
btn1.onclick = function() {
// access the saved reference to the MyComponent instance
self.fx1();
}
}
答案 1 :(得分:1)
另一种方法:
MyComponent.prototype.fx2 = function() {
var btn1 = document.getElementById('Button1');
btn1.onclick = (function() {
this.fx1();
}).bind(this);
}