代码之家  ›  专栏  ›  技术社区  ›  jim

使用回调编写Javascript this和that

  •  0
  • jim  · 技术社区  · 8 年前

    var that = this 对于回调,为什么回调函数必须是 function() {that.myFn()} 而不是 that.myFn

    var obj = {
    
      foo: function(fn) {
        console.log('--foo--', this);
        fn();
      },
    
      bar: function() {
        console.log('--bar--', this);
      },
    
      render: function() {
        var that = this;
    
        // this line works
        this.foo( function() {that.bar()} );
    
        // this line doesn't work
        this.foo(that.bar);
      }
    
    }
    
    obj.render()
    
    3 回复  |  直到 8 年前
        1
  •  2
  •   slackOverflow    8 年前

    当您在属性上调用函数时,如

    myObject.myFunction();
    

    它自动绑定 this 值,而只需获得对该函数对象的引用,如下所示:

    var x = myObject.myFunction;
    x();
    

    将其包装到如下函数中:

    var x = function(){ myObject.myFunction()};
    x();
    

    var x = myObject.myFunction.bind(myObject, parameterOneIfAny);
    x();
    

    它返回一个函数,其显式绑定“this”值为“myObject”。它只是javascript函数系统的一部分,函数对象不保存“this”上下文(或者更确切地说是默认值) object.function() 或明确与 object.function.bind(object)

    new 如中所示

    var x = myObject.myFunction.bind(myObject, parameterOneIfAny);
    var y = new x();
    

    被实例化为新对象,并作为返回值传递,这是javascript伪“类”语法的基础。因此,在本例中,x作为构造函数调用,其

    window 对象

        2
  •  2
  •   Patrick Roberts Benjamin Gruenbaum    8 年前

    原因是因为 that.bar() bar.call(that) 但是 fn() fn.call(undefined) in loose mode, undefined becomes the global context window

        3
  •  -1
  •   Planetary Dev    8 年前

    正如@slackOverflow所说。这里有一个链接,有助于理解 https://developer.mozilla.org/de/docs/Web/JavaScript/Referen‌ce/Operators/this

    或者试试这个。这是一个很好的帖子,可能也会有所帮助。 http://ryanmorr.com/understanding-scope-and-context-in-javas‌​cript