What does “this” refer to in a call statement in a function, as a method of another function

后端 未结 1 1800
青春惊慌失措
青春惊慌失措 2021-01-17 04:17

If I see a code with constructor functions like this:

function F(){}
F.prototype.k = \"v\";

function F2(){
    F.call(this);
}

What does \

相关标签:
1条回答
  • 2021-01-17 04:40

    this in any function is determined by how the function is called and you do not show how F2() is called, but what this code is doing is saying that whatever this is set to in F2, use the same value for this when F() is executed.

    1. If F2() is called just like this F2(), then this will be either the global object (window in a browser) or undefined (if running in strict mode).

    2. If F2 is called like:

      var obj = new F2();

      Then, this would be set to the a newly created instance of F2.

    3. The methods F2.apply(x) and F2.call(x) can determine what this will be set to in a given function based on what you pass as the first argument.

    4. If it's a method call as in obj.method(), then this is set to the obj.

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