1

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.

RobG
  • 124,520
  • 28
  • 153
  • 188
Hind Forsum
  • 8,077
  • 8
  • 40
  • 88
  • 1
    Then you're not in the global scope or in any scope where `this` is not `window`. The `o` object isn't used in either example. If you run that code in the global scope, you'll get `'red'` both times. In NodeJS, if you're in a module, then you're not in the global scope. –  Aug 08 '16 at 02:39
  • If you run the browser code as global code, you'll get "red" for both calls to *say*. – RobG Aug 08 '16 at 03:43

1 Answers1

1

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:

Community
  • 1
  • 1
V. Panchenko
  • 696
  • 7
  • 29