不同的行为关键字"这&Q​​UOT; node.js中与浏览器之间 [英] different behavior of keyword "this" between node.js and browsers

查看:104
本文介绍了不同的行为关键字"这&Q​​UOT; node.js中与浏览器之间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试着按照即code,Firefox和Node.js的

I've tried following code in ie, firefox and node.js

var x = 10;
var o = { x: 15 };
function f(){
     console.log(this.x);
}
f();
f.call(o);

在浏览器中的结果是10,15,但结果在node.js中未定义,15

the results in browsers are 10, 15, but the result in node.js is undefined, 15.

请给我解释一下什么是浏览器和node.js的本关键字的不同的行为?我读过很多页,但根本没有什么明显的答案。
先谢谢了。

Please explain to me what is the different behavior of "this" keyword in browsers and node.js? I've read many pages but there wasn't any obvious answer. Thanks in advance.

推荐答案

在加载的NodeJS的Javascript文件会自动包装在匿名函数。

Javascript files loaded in Nodejs are automatically wrapped in anonymous functions.

所以在节点你真正运行是:

So in Node what you are really running is:

(function(/* There are args here, but they aren't important for this answer */){
  var x = 10;
  var o = { x: 15 };
  function f(){
    console.log(this.x);
  }
  f();
  f.call(o);
})();

浏览器不这样做。问题是,现在的节点 X 只是在功能范围的普通变量,它不是全球范围的一部分。当你调用 F()这样,这个˚F是全球范围。

The browser does not do this. The issue is that now in Node x is just a normal variable in the scope of the function, it is not part of the global scope. When you call f() this way, this within f is the global scope.

如果直接把 X 在全球范围内,它会在两种情况下工作。

If directly put x on the global scope, it will work in both cases.

this.x = 10;

这将会把 X 窗口全局对象在浏览器中,而全球节点中的全局对象。

That will place x on the window global object in the browser, and the global global object in Node.

一般情况下,你没有在全球范围内节点的负载的东西,而不是你的组code到模块,的此处描述。有一个关于你可以在这里访问全球不同的东西的信息。如果你是好奇的包装,你可以看到它这里

Generally, you do not load things globally in Node, instead you group your code into modules, as described here. There is info about the various global things you can access here. And if you are curious about the wrapper, you can see it here.

这篇关于不同的行为关键字"这&Q​​UOT; node.js中与浏览器之间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆