How to pass context to anonymous function?

后端 未结 2 1594
灰色年华
灰色年华 2021-01-31 17:15

There are some function, thats do something long work and its provides callback.

someFunc: function(argument, callback, context) {
  // do something long

  // c         


        
2条回答
  •  深忆病人
    2021-01-31 17:59

    Use Function.prototype.call to invoke a function and manually set the this value of that function.

    someFunc: function(argument, callback, context) {
        callback.call(context); // call the callback and manually set the 'this'
    }
    

    Now your callback has the expected this value.

    someFunc('bla-bla', function () {
      // now 'this' is what you'd expect
        this.anotherFunc();
    }, this);
    

    Of course you can pass arguments like normal in the .call invocation.

    callback.call(context, argument);
    

提交回复
热议问题