【发布时间】:2016-11-07 00:06:39
【问题描述】:
我有一个构造函数(或类,如果你愿意的话),我的部分代码正在运行一个间隔。我正在尝试清除间隔,但在 countDown 函数中无法访问 countDown 变量。
请注意: countDown 和 startTimer 函数都在构造函数中。
代码如下:
this.startTimer = function() {
if (!isOn) {
timeFormatter();
if (timeArray[0] === "0") {
return error(" You need to work longer than that! ")
}
isOn = true;
var startCountDown = setInterval(this.countDown.bind(this),1000);
}
}
this.countDown = function() {
//Once timer ends, stop function.
if (timeArray[0] === 0
&& timeArray[2] === 0
&& timeArray[3] === 1) {
element.innerHTML = 0;
counter = 0;
isOn = false;
clearInterval(startCountDown) //I get error here. countDown is not accessible.
return null;
}
}
【问题讨论】:
-
如果你在 startTimer 函数中访问 countDown ,它只在这个范围内可用。如果您希望 var 可全局访问,请全局定义它(在函数范围之外)。
-
添加到@Lupinity 的评论:将其声明为您班级的成员。还有,不要叫countDown,会和
countDown函数冲突 -
如果我在函数之外定义它,那么它会更早触发,我需要它在启动计时器函数中触发。我想避免使用未定义的全局变量。
-
@Tibrogargan 你能解释一下你的意思吗?
-
@theNeighbourhoodGhost
countDown是this的属性。即使您在全局范围内或作为其中的成员声明了一个单独的变量,您也会遇到名称冲突。您不能有两个具有相同名称的标识符 - 一个会隐藏另一个。您尤其不能拥有两个同名的属性。您无法访问在 startTimer 函数中声明的var countDown,因为该声明的范围是本地的。同样,即使它是全局的,您也无法访问它,因为this.countDown会隐藏它
标签: javascript oop scope