Search code examples
javascriptscopewindowthisglobal

Javascript "apply" function seems not working for global "this"?


I tested the scope of 'this' keyword, in nodejs:

color = 'red';
var o = {
    color: 'blue'
};

function say() {
    console.log(this.color);
};
say.apply(this);  //'undefined'
say.apply(global);//'red'

In browser:

color = 'red';
var o = {
    color: 'blue'
};

function say() {
    alert(this.color);
};
say.apply(this);  //'undefined'
say.apply(window);//'red'

var color = 'red';
function say() {
  alert(this.color);
}
say.apply(this);   //'red'
say.apply(window); //'red'

The result is a bit weird to me: as long as "this" is a pointer to "global" or "window", why say.apply(this) will output 'undefined'?

Thanks.


Solution

  • In this case your this is really underfined, because color = 'red'; has this equivalent: global.color = 'red';. To make it related with this you need to do it by yourself: this.color = 'red';

    To get value of color from o object you need to write something like this:

    say.apply(o);

    This is the good example of using apply():

    function printArgs() {
      var join = [].join; // copy link of array.join into variable
    
      // call join with "this=arguments",
      // this call is equivalent with "arguments.join(':')"
      // here we have guarantee that method 'join()' was called from 'arguments'
      // (not from other object)
      var argStr = join.apply(arguments, [':']);
    
      console.log( argStr ); // output will looks like '1:2:3'
    }
    
    printArgs(1, 2, 3);
    

    Also you can find useful information here: