Search code examples
javascriptnode.jsgoogle-chromethisv8

V8 javascript: chrome vs node.js - differences in 'this' context


Take a look at the code below:

var pocket = {
        cash: 1000,
        showCash: function() {
                return this.cash;
        }
};

var thomas = {
        name: "Thomas",
        work: function() {
                console.log('I don\'t want to, but I have to... work!');
        },
        cash: 5000
};

var bird = {
        fly: function() {
                console.log('I\'m flying!');
        }
};

console.log(pocket.showCash());

thomas.showCash = pocket.showCash;
console.log(thomas.showCash());

bird.showCash = pocket.showCash;
console.log(bird.showCash());

var cash = 20;
var showCashFun = pocket.showCash;
console.log(showCashFun());

The code is very simple and displays how does the engine interpret this keyword. When I run it inside chrome console, I get following output:

1000
5000
undefined
20

And that's ok - I understand it all. But when I run it in node.js console, I get:

1000
5000
undefined
undefined

Both chrome and node.js use v8. How come there is such difference?

edit: in case it makes any difference, my node version is v0.10.8 and chrome is 27.0.1453.93.


Solution

  • In node.js code runs in module wrapper so variables are not accidentally global. In Chrome and any other browser you need to do this wrapping yourself otherwise every variable you create is global.

    When you call a function directly then this will be the global object inside the function for that call under non-strict mode.

    All global variables are properties of the global object, so you can access the global variable cash through the .cash property of the global object.