关于javascript:在Node中,这个内部函数等于undefined

In Node, this inside function equals undefined

本问题已经有最佳答案,请猛点这里访问。

在node中,我怎么会在这个例子中未定义?

因为我没有使用严格模式,所以应该可以从函数内部访问它,并等于全局对象。

1
2
3
4
5
6
7
this.foo ="bar";

function fun () {
    console.log(this.foo);
}

fun(); // undefined


参见MDN中有关"use strict"模式的片段。

First, the value passed as this to a function in strict mode is not forced into being an object (a.k.a."boxed"). For a normal function, this is always an object: either the provided object if called with an object-valued this; the value, boxed, if called with a Boolean, string, or number this; or the global object if called with an undefined or null this... for a strict mode function, the specified this is not boxed into an object, and if unspecified, this will be undefined:

有关最佳解释和示例,请参阅参考:"安全"javascript(MDN)

另请参见stackoverflow中的本文:在node.js中,如何解释"use strict"语句?