简体   繁体   English

V8 JavaScript:Chrome与Node.js-“此”上下文的差异

[英]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. 该代码非常简单,并显示引擎如何解释this关键字。 When I run it inside chrome console, I get following output: 当我在chrome控制台中运行它时,得到以下输出:

1000
5000
undefined
20

And that's ok - I understand it all. 没关系-我了解全部。 But when I run it in node.js console, I get: 但是,当我在node.js控制台中运行它时,我得到:

1000
5000
undefined
undefined

Both chrome and node.js use v8. chrome和node.js都使用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 . 编辑:如果有什么不同,我的节点版本是v0.10.8而chrome是27.0.1453.93

In node.js code runs in module wrapper so variables are not accidentally global. 在node.js中,代码在模块包装器中运行,因此变量不会是意外的全局变量。 In Chrome and any other browser you need to do this wrapping yourself otherwise every variable you create is global. 在Chrome和其他任何浏览器中,您都需要这样做,否则您创建的每个变量都是全局变量。

When you call a function directly then this will be the global object inside the function for that call under non-strict mode. 当您直接调用函数时, this将是非严格模式下该调用的函数内部的全局对象。

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. 所有全局变量都是全局对象的属性,因此您可以通过全局对象的.cash属性访问全局变量cash。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM