0

I was create these functions to check what the "this" is in every function, and want to konw that when use the call function,why the "this" is not the "test" object?

function foo() {
        console.log("call foo:", this);
        bar();
    }

function bar() {
    //why the "this" is not the "test" object
    console.log("call bar:", this);
}

function Test() {

}

var test = new Test();
foo.call(test);
Oneday
  • 3
  • 1

1 Answers1

5

If you do foo.call(test), then inside of foo(), this will be test.

But, inside of foo(), when you then call bar(), the this value will then be reset inside of bar() to its default value.

EVERY function call in Javascript sets a new value of this according to how the function is called.

A plain function call such as bar(), sets the value of this to the global object if not running in strict mode or to undefined if running strict mode.

To review, the methods for setting the this value to something specific are:

foo.call(test, ...);      // sets this to test
foo.apply(test, ...);     // sets this to test

obj.method();             // sets this to obj

var x = foo.bind(test);   
x();                      // sets this to test

var x = new foo();        // create a new object and sets this to the new object

foo();                    // this set to global object or undefined (in strict mode)

Just remember that the value of this is reset on every function call in Javascript according to the above rules. It is never "inherited" from the previous value. It is always set to something new on every function call based on how the function call was made. This is a common misunderstanding for people new to Javascript (I was tripped up by the same thing many moons ago).

It is also worth noting that a callback function may have the value of this set to something specific (using .apply() or .call() internally) when the callback function is called. For example:

function submitHandler(e) {
   // value of this is in this function is set
   // by addEventListener to the DOM object that handled the event
}

document.getElementById("submit").addEventListener("click", submitHandler);

Other references on the topic:

When you pass 'this' as an argument

A Better Understanding of This

How does the "this" keyword work?

Community
  • 1
  • 1
jfriend00
  • 580,699
  • 78
  • 809
  • 825
  • thank you for your answer! !!And can I think the result with scope chain: If do foo.call(test), then inside of foo(), "this" will be test.,and inside of foo(), when then call bar(),because test object has not bar() method, so it will search the scope chain and found it in window object.[scope chain](http://dmitrysoshnikov.com/ecmascript/chapter-4-scope-chain/)(sorry my English is not good to express myself) – Oneday Feb 04 '15 at 06:09