Javascript, preserving this reference when passing function argument

前端 未结 2 1152
栀梦
栀梦 2021-01-19 07:00

I\'m inside a function of an object and I need to call an external function and pass a reference to a function as argument. This last function argument uses the keyword

相关标签:
2条回答
  • 2021-01-19 07:37

    There is one other option available to you, if you're on a recent enough browser and that is to use Function.bind.

    This allows you to create a function that has been bound to a specific scope. Put another way, it allows you to define what this will be, inside that function. Thus, you could do it this way.

    MyObj.prototype.doSomething= function(){
       externalFunction(this.someVar, this.internalFunc.bind(this, data));
    };
    

    Follow the link above and scroll to the bottom to see information about browser support.

    Edit

    Actually, there's one other option, which is to use one of the many libraries and frameworks that are out there. Any one worth its salt will have a bind, hitch, proxy or otherwise available to you. However, all these are doing are wrapping up the native JS approaches, but they often provide useful additions that make this technique even more valuable.

    0 讨论(0)
  • 2021-01-19 07:40

    Assigning this to a local variable is fine and common.

    Many libraries make your second approach easier by providing a method that returns a wrapper function and sets the execution context, e.g. $.proxy in jQuery (or _.bind in underscore.js).

    0 讨论(0)
提交回复
热议问题