function first() {
var a = "Hello";
console.log( this.a );
}
first(); // undefined
为什么下面的函数未定义到控制台?不应该抛出a
未定义的错误吗?
答案 0 :(得分:4)
在非严格模式下,this
会引用window
,因此this.a
将等于window.a
。
在第一行使用'use strict'
尝试此操作。
// Original
function first() {
var a = "Hello";
console.log(this == window)
}
first();
// Strict example
(function(){
'use strict'
function first() {
var a = "Hello";
try {
console.log(this.a)
} catch(e){
console.log(e.message)
}
}
first();
})();
// Class-like example
function First() {
this.a = "Hello";
console.log(this.a)
return this
}
new First();

答案 1 :(得分:0)
正如您所说 a未定义,这意味着它是undefined
。每当您尝试从对象访问属性时,如果该对象不存在,则将抛出该错误,但是,如果该属性不存在,则将返回undefined。
在上述示例中,尝试在浏览器控制台中运行并记录this
,它指向window
对象。因此,this.a
将尝试从窗口对象访问该属性,找不到该属性将返回undefined
。
var a = "Hi";
function first() {
var a = "Hello";
console.log(this.a)
}
first(); // Hi

错误情景
function first() {
var a = "Hello";
console.log(obj.a) // throws error
}
first();

答案 2 :(得分:0)
您需要使用此而不是 var 。
function first() {
this.a = "Hello";
console.log(this.a);
}
first(); // "Hello"
如果你想在对象第一个的范围内创建变量,那么修改代码
function first() {
this.a = "Hello";
this.b = function() {
console.log(this.a);
}
}
obj = new first;
obj.b();