a.js文件如下
'use strict'
// node js运行代码
var msg;
msg='a'
console.log(msg)
console.log(module)
console.log(this) //输出空对象
function f2(){
console.log(this)// 输出结果未确定
}
new f2() // f2中的this是一个空对象,表示当前创建的对象,log 输出{}
f2()// 输出undefine,
node a.js 执行a.js文件
问题:
- 为什么 console.log(this) 会输出 输出空对象
- 在模块中,顶层this关键字返回undefined 而不是windows。如何理解这句话
- 为什么 f2()输出 输出undefine,
求指点
首先
NodeJS
环境并没有Window
这个对象。在浏览器中直接输入
console.log(this)
则会打印Window
。然后构造函数中,
this
指向new
出来的那个新的对象。最后在函数中,
this
永远指向最后调用他的那个对象。所以最后为什么为输出
undefined
其实就是没有调用的那个对象。如果你改写成下面这样,就会输出调用它的
test
对象了。