gpt4 book ai didi

javascript - 从回调调用方法时如何从方法中获取正确的类上下文

转载 作者:行者123 更新时间:2023-11-29 18:24:26 26 4
gpt4 key购买 nike

我正在使用 Class.js用于创建类。

当从回调函数调用时,我没有在方法中获得正确的上下文

我的代码是

WordCloud = MyClass.extend({
init: function(data) {
var me = this;
(......).on("onComplete", this.draw);
},
show: function(word) {
alert(word)
},
draw : function(words){
console.debug(this); // prints element that triggred `onComplete` action
console.debug(words); // "Hi"
console.debug(me); // me is not defined
me.show(words) // Need to call this method
}
});

问题是 draw 方法在 Action 完成时触发,但在 draw 方法内部 this 不是实际的 class 实例,但是触发回调操作的元素。

我无法在调用 this.draw 时传递 exta 参数,因为它是一个回调函数,而 onComplete 只有一个参数。

如何从draw调用show方法?

最佳答案

如果您不必支持 Internet Explorer 8 或更低版本,您可以使用 bind() :

init: function(data) {
var me = this;
(......).on("onComplete", this.draw.bind(this));
}

否则,如果您已经在使用 jQuery,则可以利用 $.proxy() ,其工作方式相同:

init: function(data) {
var me = this;
(......).on("onComplete", $.proxy(this.draw, this));
}

关于javascript - 从回调调用方法时如何从方法中获取正确的类上下文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14939105/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com