Javascript函数对象在NODEJS中调用()

我已经通过call()方法读了下面的全局输出。 在这种情况下,“迈克尔”不应该是this.name。 但是显示的输出是不确定的。

—新信息:这是通过NODEJS运行—

function sayNameForAll(label) { console.log(label + ":" + this.name); } var person1 = { name: "Nicholas" }; var person2 = { name: "Greg" }; var name = "Michael"; sayNameForAll.call(this,"global"); //ouput global:undefined sayNameForAll.call(person1,"PersonName1"); //PersonName1:Nicholas sayNameForAll.call(person2,"PersonName2"); //PersonName2:Greg 

原因可能是在这方面, this不是同一个范围。 这可能是由于几个原因而发生的:

  • 你正在运行这个函数(甚至(function() { self invoking function })()
  • 你在nodejs中运行这个,而不是在浏览器中,在节点中,在全局范围内, thisundefined ,而不是浏览器中的window

在这里工作正常(点击运行代码)。

你的代码在另一个函数内运行吗? 如果是,那么你声明的variables将不在全局对象上,并且取决于你如何调用该函数, this可能不涉及全局对象。

 function sayNameForAll(label) { console.log(label + ":" + this.name); } var person1 = { name: "Nicholas" }; var person2 = { name: "Greg" }; var name = "Michael"; sayNameForAll.call(this,"global"); //ouput global:undefined sayNameForAll.call(person1,"PersonName1"); //PersonName1:Nicholas sayNameForAll.call(person2,"PersonName2"); //PersonName2:Greg