ETA:我不认为这个问题是所链接问题的重复。我知道如何返回私有变量(如下代码所示),这个问题是关于如何在同一对象内调用私有函数的。
我在查找有关javascript的相关信息时遇到了麻烦。我声明了一个对象,并且在该对象中声明了四个函数(三个是对象方法,一个不是),我想使第四个成为对象方法,以便可以与jquery(timer.displayTime)分开调用();),但是当我执行startIntervalTimer时,该功能的使用将停止工作。我要做什么甚至有可能吗?
var startStopTime = function() {
//This function is currently called inside startIntervalTimer();
function displayTime() {
//Display correct time
};
//I WANT SOMETHING LIKE THIS INSTEAD BUT (SEE startIntervalTimer)
this.displayTime = function() {
//Display correct time
}
var intervalTimer;
this.startIntervalTimer = function() {
console.log(timeSetMS);
intervalTimer = setInterval(function() {
if(timeSetMS > 0) {
timeSetMS -= 1000;
displayTime(); //THIS IS WHERE AND HOW IT IS CALLED
this.displayTime(); //THIS IS WHAT I'M GOING FOR, BUT IT WON'T WORK
console.log(timeSetMS);
} else if(timeSetMS <= 0) {
clearInterval(intervalTimer);
console.log("timer stopped");
}
}, 1000
);
}
};
然后在jQuery中,我有:
var timer = new startStopTime();
$("#timer-container, #timer-label").click(function() {
if(power == "off") {
power = "on";
timer.startIntervalTimer();
} else if (power == "on") {
power = "off";
timer.stopTimer();
}
});
//I want to add this, below
$("#session-length").click(function() {
//Change the display
timer.displayTime();
displayTime(); // This won't work obviously because it's out of scope
});
最佳答案
您可以在对象内部声明另一个变量,即。 self
:
var startStopTime = function() {
//declare self
var self = this;
this.displayTime = function() {
//Display correct time
}
var intervalTimer;
this.startIntervalTimer = function() {
console.log(timeSetMS);
intervalTimer = setInterval(function() {
if(timeSetMS > 0) {
timeSetMS -= 1000;
displayTime();
self.displayTime(); // use self instead
console.log(timeSetMS);
} else if(timeSetMS <= 0) {
clearInterval(intervalTimer);
console.log("timer stopped");
}
}, 1000
);
}
};
关于javascript - 我可以从同一对象javascript中调用私有(private)函数吗,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/41367775/