我有下一段代码:
function Server() {
this.isStarted = false;
// var isStarted = false;
function status() {
return isStarted;
}
console.log(status());
}
var a = new Server()
当我运行它时,我得到了
ReferenceError: isStarted is not defined
at status (/a/fr-05/vol/home/stud/yotamoo/workspace/ex4/text.js:7:10)
at new Server (/a/fr-05/vol/home/stud/yotamoo/workspace/ex4/text.js:10:14)
at Object.<anonymous> (/a/fr-05/vol/home/stud/yotamoo/workspace/ex4/text.js:
但是,如果我将this.isStarted = false;
更改为var isStarted = false;
,一切正常。
有人在乎解释原因吗?
由于
答案 0 :(得分:2)
这引起了某事的拥有者的注意。请参阅此article。 var声明一个局部变量。
在您的情况下,您想要参考知道服务器是否已启动,因此您需要将“this”添加到状态函数中。
function status() {
return this.isStarted;
}
答案 1 :(得分:0)
长话短说。由于isStarted
,当定义为this.isStarted = true
时,是当前对象的属性(JavaScript this
关键字是指调用函数的对象),在status
函数中必须以this.isStarted
访问它。
将其声明为变量(var
)是不同的。从技术上讲,isStatus
将成为隐藏词法范围对象的属性。您必须在整个isStatus
函数体和所有子函数中仅以Server
的形式访问它。