如何获得回调以使用“this”在类范围 [英] How to get callback to work with "this" in class scope
问题描述
我有一个关于下面的代码打印出this.text的问题。我需要有一个包装函数,使其工作。这太麻烦了。有没有一个更简单的方法(没有额外的包装)得到它的工作?
I have a question about following code to print out "this.text". I need to have a wrapper function to make it work. This is too troublesome. Is there a simpler way (without additional wrapper) to get it work?
感谢
function Class1() {
this.text = "test";
}
Class1.prototype.show = function() {
console.log(this);
console.log(this.text);
}
var testClass = new Class1();
function funWithCallBack(cb) {
cb();
}
// it will show "undefined" because "this" scope changes to window
funWithCallBack(testClass.show);
function wrapper() {
testClass.show();
}
// this one will work but troublesome
funWithCallBack(wrapper)
推荐答案
您可以使用如下匿名函数:
You can use an anonymous function like this:
// it will show "undefined" because "this" scope changes to window
funWithCallBack(testClass.show);
:
// anonymous function to use the right object for the method
funWithCallBack(function() {
testClass.show()
});
出现您的问题,因为当您通过 testClass.show
作为回调,它只是获取函数引用,并且与 testClass
没有任何关联。但是,您可以创建一个临时函数,使用将它们绑定在一起 .bind()
,但是在一些旧版本浏览器中不支持,因此我一般只使用匿名函数。
Your problem occurs because when you pass testClass.show
as the callback, it just gets the function reference and there is no association with testClass
any more. But, you can create a temporary function that binds them together using .bind()
, but it isn't supported in some older browsers which is why I generally just use the anonymous function.
.bind()
实现将如下所示:
// use .bind() to make sure the method is called in the right object context
funWithCallBack(testClass.show.bind(testClass));
这篇关于如何获得回调以使用“this”在类范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!