I have this code below:
this.color = "red";
var o = {color: "blue"};
function sayColor() {
console.log(this.color);
}
sayColor();
sayColor.call(this);
sayColor.call(o);
@Jim Deville,
here are the new discoveries:
node functionTypeThisExample.js
in terminal, it outputs "undefined, red, blue".so my question is what happens in last situation?
this
in node is no different than this
in JS. It is the object representing the current context.
this.color = "red";
Here, this is the global object
var o = {color: "blue"};
function sayColor() {
console.log(this.color);
}
sayColor();
In this case, this is still the global object
sayColor.call(this);
This is the global object, but applied via call, not "by default"
sayColor.call(o);
This is o
When I run it in node (0.6.18 on OS X), though, I get "red, red, blue" like you do in the browser.