Javascript 匿名事件处理程序不';我无法使用原型方法
无法从匿名函数处理程序中的fx2访问fx1Javascript 匿名事件处理程序不';我无法使用原型方法,javascript,Javascript,无法从匿名函数处理程序中的fx2访问fx1 var MyComponent = function () { //my constructor } MyComponent.prototype.fx1 = function() { //code } MyComponent.prototype.fx2 = function() { var btn1 = document.getElementById('Button1') btn1.onclick = function(
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.
}
}
由于
此
绑定到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();
}
}
由于
此
绑定到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();
}
}
另一种方法是:
MyComponent.prototype.fx2 = function() {
var btn1 = document.getElementById('Button1');
btn1.onclick = (function() {
this.fx1();
}).bind(this);
}
另一种方法是:
MyComponent.prototype.fx2 = function() {
var btn1 = document.getElementById('Button1');
btn1.onclick = (function() {
this.fx1();
}).bind(this);
}
那么你到底尝试了什么?你是如何访问它的?你把代码漏掉了question@devnull69-OPs注释
试图从此处调用fx1,但无法访问它。
表示他使用了this.fx1()但是在他的模型中出现了一个输入错误。那么你到底尝试了什么?你是如何访问它的?你把代码漏掉了question@devnull69-OPs注释试图从此处调用fx1,但无法访问它。
表示他使用了this.fx1()但是在他的模型中出现了一个输入错误。如果我们继续回答那些一开始就没有表现出OP努力的问题,问题不会变得更好。但是现在一切都好了,请便:-)@devnull69老实说,我立刻明白了问题的含义,这对我来说已经足够明显了。顺便说一句,作为社区的一员,你现在知道了问题的内容,非常欢迎你改进这个问题。如果我们继续回答那些一开始就没有表现出OP努力的问题,问题不会变得更好。但是现在一切都好了,请便:-)@devnull69老实说,我立刻明白了问题的含义,这对我来说已经足够明显了。顺便说一句,作为社区的一员,你现在知道这个问题是关于什么的,非常欢迎你改进这个问题。