【问题标题】:How to get callback to work with "this" in class scope [duplicate]如何让回调在类范围内使用“this”[重复]
【发布时间】:2017-03-03 02:16:48
【问题描述】:

我有一个关于打印“this.text”的代码的问题。

我需要一个包装函数来使它工作。这太麻烦了。

有没有更简单的方法(没有额外的包装器)让它工作?

  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)

【问题讨论】:

    标签: javascript callback


    【解决方案1】:

    你可以像这样使用匿名函数:

    // 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() 创建一个将它们绑定在一起的临时函数,但在一些旧浏览器中不支持它,这就是为什么我通常只使用匿名函数。

    .bind() 实现如下所示:

    // use .bind() to make sure the method is called in the right object context
    funWithCallBack(testClass.show.bind(testClass)); 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-12-09
      • 1970-01-01
      • 2023-03-29
      • 2014-01-04
      • 2010-09-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多