"use script";
var user = {
name: "John Doe",
career: "Civil Engineer",
socialMedia: {
fb: "www.facebook.com/johndoe",
twitter: "www.twitter.com/johndoe"
},
about: function() {
console.log("My name is " + this.name + " and I am a " + this.career);
}
}
var name = "Jen";
var career = "Dentist";
user.about();
var newAction = user.about;
newAction(); // My name is undefined and I am a undefined
为什么newAction()
会返回未定义的名称和职业,但是当我从var
删除{<1}}时
var name = "Jen";
var career = "Dentist";
到
name =&#34; Jen&#34 ;; 职业=&#34;牙医&#34 ;;
然后我再次执行newAction()
并获得:
newAction() // My name is Jen and I am a Dentist
答案 0 :(得分:1)
nodejs代码不在全局范围内运行,而是在某种函数实例中运行:
//(function(module){
var some=5;
console.log(global.some);//undefined
//})(..)
因此,如果你声明一个变量,它不是这个引用的全局的一部分,它只是在不可见的函数范围内(这与浏览器中的var有所不同)最高范围是窗口的一部分。
如果你遗漏了声明(不好,不是严格的模式),它将全局范围内,因此成为函数中全局又 this 的一部分。可能会这样做:
global.name="John";
newAction();//this===global
The 'this' keyword behaves differently in Nodejs and browser