关于javascript:浏览器和node中的this作用域问题

8次阅读

共计 1278 个字符,预计需要花费 4 分钟才能阅读完成。

之前面试遇到一道题,问

function a(){this.b=5;}
var b=9;
a();
console.log(b)

请问 b 的输入是多少?过后简略的答复了是 5。然而这并非是正确的答案,应该从 js 的运行环境说起。
先说一下运行后果:
在 node 上咱们失去的后果是 9
而在浏览器上咱们失去的后果是 5
为什么是这样呢,咱们首先晓得一个 js 的规定:

A global variable is a variable that is declared in the global scope in other words, a variable that is visible from all other scopes. In JavaScript it is a property of the global object.

一个全局变量是在全局作用域被申明的变量,对于其它所有的作用域可见。在 javascript 中,全局变量是 全局对象的一个属性
咱们晓得在浏览器中的全局变量是 window,那么在全局作用域申明的变量是全局属性,全局属性也是一个全局变量。在题目中, 运行 a 时,this 指向的是全局变量window,即

this.a===window.a===var a;

因而执行 a 函数之后,全局变量 b 变为了5;

那么在 node 中呢,node 中的一个 js 实际上是一个模块,咱们首先说分明 node 中的 this 指向问题

this.a=6;
(function(){this.a=6;})();

函数外 this 的指向和函数内 this 的指向是不同的,函数外的 this 指向的是该模块,即

this===module.exports

而立刻执行函数内的 this 指向的是 node 执行环境中的全局变量global

而后咱们再说说 node 中的模块是怎么执行的

function Module() {   //  Node 模块治理类
    this.exports = {};}

function Fun(exports, require, module, __filename, __dirname) {   //  自定义模块包装后
    var x = 1;

    console.log(module.x);  // undefined
    console.log(exports.x);  // undefined
    console.log(this.x);  // undefined

    console.log(this === module);  // false
    console.log(this === exports);  // true

}

var module = new Module();    //  实例化
var exports = module.exports;
var options = [exports, require, module, filename, dirname];

Fun.apply(exports, options);   //  自定义模块实例化

咱们能够发现在 node 中一个模块内用 var 申明的变量实际上是一个函数中用 var 申明的变量,它并不是全局变量。由作用域链咱们可知,函数作用域中的 b 笼罩了全局作用域中的b,由此在 node 中输入的是9.

参考

  • MDN global variable
  • 对于 node 中 var 一个变量
正文完
 0