关键字& quot; this& quot;的不同行为在node.js和浏览器之间 [英] different behavior of keyword "this" between node.js and browsers

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

问题描述

我已经尝试过以下代码,例如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中"this"关键字的不同行为是什么?我读了很多书,但是没有明显的答案.预先感谢.

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.

所以在Node中,您真正正在运行的是:

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 中的 this 是全局范围.

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 放置在浏览器中的 window 全局对象上,并将 global 全局对象放置在Node中.

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

通常,您不会在Node中全局加载内容,而是将代码分组为模块,例如此处上获取有关各种全局性内容的信息.而且,如果您对包装器感到好奇,可以在此处.

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.

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

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