Assiging a method to a variable in Javascript

后端 未结 1 2014
再見小時候
再見小時候 2021-01-25 12:24

In my example below based on some conditions I should either call foo method from my class or foo method from alternative.js; I\'m assigning method in myFunc variable and call t

相关标签:
1条回答
  • 2021-01-25 12:48

    You can use .bind() to bind the object to the method call. For example, if you're trying to save a method of a specific object into myFunc, then you can do this:

    myFunc = myClass.foo.bind(myClass);
    

    Then, when you later do:

    myFunc(...);
    

    it will actually use the object reference myClass to call it properly as a method.

    See the MDN reference on .bind() for more details.

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