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:
- when I run that code snippet in browser: it outputs “red, red, blue”, continuously.
- when I run it directly in node terminal: it also outputs “red, red, blue”, continuously.
- but when I save that code in as a file functionTypeThisExample.js, and execute
node functionTypeThisExample.jsin terminal, it outputs “undefined, red, blue”.
so my question is what happens in last situation?
thisin node is no different thanthisin JS. It is the object representing the current context.this.color = "red";Here, this is the global object
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
oWhen I run it in node (0.6.18 on OS X), though, I get “red, red, blue” like you do in the browser.