Why is some_func(…) != some_func.call(this, …) in a constructor

后端 未结 1 1582
一个人的身影
一个人的身影 2021-01-14 12:55

I always assumed that some_function(...) was exactly the same as some_function.call(this, ...). This seems not to hold true for calls in construc

相关标签:
1条回答
  • 2021-01-14 13:22

    Calling a function with .call is different from just invoking it with (). With .call you explicitly set the value of this for the call in the first argument. With normal invocation, the this value will implicitly be the global object or undefined, depending on whether strict mode is enabled or not.

    func.call({}, 1); //Call the function func with `this` set to the object and pass 1 as the first argument
    
    func(1); //Call the function func with 1 as the first argument. The value of this inside the function depends on whether strict mode is on or off.
    

    See .call


    I always assumed that some_function(...) was exactly the same as some_function.call(this, ...). This seems not to hold true for calls in constructors / an object construction context:

    That's not true, they are never the same. You are probably confusing it with calling a function as a property of some object. obj.method() will mean that obj is the value of this for the method call and it would be effectively the same as obj.method.call(obj).

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