Why do javascript work on websites and sites have different results?

I updated my Node.Jsin version 7.6.0and launched google chrome version 57.0, on the other hand.

When I run this javascript code snippet, I get two different results, as shown below:

    'use strict'
    
    var obj = {
        id: "awesome",
        cool: function coolFn() {
            console.log(this.id);
        }
    };
    var id = "not awesome";
    obj.cool(); //awsome
    
    setTimeout(obj.cool, 100);
Run code

chrome result:

awesome
not awesome

node.js result:

awesome
undefined

Entry at https://nodejs.org/en/docs/es6/ I even used the flag --harmony, but the result of node.js has not changed.

+6
source share
1 answer

When node runs your file, it is processed as a module, and the documents say it is effectively wrapped:

(function (exports, require, module, __filename, __dirname) {
  // Your module code actually lives in here
});

, var id = "not awesome"; .

, this . , var id , , node undefined.

, :

(function() {
    'use strict'
    
    var obj = {
        id: "awesome",
        cool: function coolFn() {
            console.log(this.id);
        }
    };
    var id = "not awesome";
    obj.cool(); //awsome
    
    setTimeout(obj.cool, 100);
})();
+4

Source: https://habr.com/ru/post/1015939/


All Articles