如何让回调与“this"一起工作?在类范围内 [英] How to get callback to work with "this" in class scope

查看:13
本文介绍了如何让回调与“this"一起工作?在类范围内的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个关于以下代码打印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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆