Node环境中的行为

时间:2014-11-10 23:05:50

标签: node.js

function a() {
return this;
}

function b() {
return this;
}

console.log(a() === b()) //true on browser and node 

但是......

function a() {
return "inside a";
}

function b() {
console.log(this.a()); //logs undefined on node, 'inside a' on browser
}

这对浏览器和节点都运行非严格模式。

1 个答案:

答案 0 :(得分:3)

this的值取决于函数的调用方式。它与如何定义函数几乎没有关系。

如果你将一个函数称为像

这样的普通函数

a()

然后,如果在严格模式下运行,函数this内的a值将是全局对象或undefined

以下是this可以控制的方式:

普通功能调用

a()

如果以严格模式运行,

this将是全局对象或undefined

方法调用

obj.a()

在这种情况下,

this将设置为对象obj

.apply()或.call()

obj.a.call(obj, arg1, arg2)
obj.a.apply(obj, array)

this将设置为作为.call().apply()的第一个参数传递的对象

.bind()

var m = obj.a.bind(obj)
m();

this将被设置为作为.bind()

的第一个参数传递的对象