【问题标题】:In Node, this inside function equals undefined [duplicate]在 Node 中,这个内部函数等于 undefined [重复]
【发布时间】:2017-02-18 03:17:00
【问题描述】:

在节点中,为什么我在这个例子中没有定义?

由于我没有使用严格模式,这应该可以从函数内部访问并且等于 Global 对象。

this.foo = "bar";

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

fun(); // undefined

【问题讨论】:

  • @Mohammad,在 Node 上是这样
  • 使用global获取全局对象。

标签: javascript node.js


【解决方案1】:

在 MDN 中查看有关 "use strict" 模式的片段。

首先,作为this 传递给严格模式下的函数的值不会被强制成为对象(也称为“装箱”)。对于普通函数,this 始终是一个对象:如果使用对象值 this 调用,则提供对象;如果使用布尔值、字符串或数字this 调用,则该值被装箱;或全局对象,如果使用未定义或空 this... 调用严格模式函数,则指定的 this 不会装箱到对象中,如果未指定,this 将未定义:

有关最佳解释和示例,请参阅参考资料: "Securing" JavaScript (MDN)

另请参阅 stackoverflow 中的这篇文章:In node.js, how the 'use strict' statement is interpreted?

【讨论】:

  • 不,node.js 本身不启用严格模式。 OP 声明他没有"use strict"
  • 你是对的@Bergi,我正在运行带有node --use_strict 标志的npm 脚本。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-07-09
  • 1970-01-01
  • 1970-01-01
  • 2016-06-02
  • 2015-10-27
  • 2014-05-21
相关资源
最近更新 更多