JavaScript 全局变量未更改
JavaScript Global Variable Not Changing
我是 JavaScript 的新手,我制作了一个简单的秒表构造函数:
function Stopwatch() {
var started = false;
var elapsed;
var start;
d = new Date();
this.duration = function() {
if (started) {
throw "Stopwatch is still running"
} else {
return (elapsed);
}
}
this.start = function() {
if (started) {
throw "Stopwatch has already started";
} else {
start = d.getTime();
started = true;
}
}
this.stop = function() {
if (!started) {
throw "Stopwatch hasn't started";
} else {
elapsed = d.getTime() - start;
started = false;
}
}
this.reset = function() {
started = false;
elapsed = 0;
}
}
let sw = new Stopwatch();
sw.start();
setTimeout(function () {
sw.stop();
console.log(sw.duration());
}, 500);
错误的逻辑工作正常,但每当我调用 sw.duration() 时,它总是 returns 零,我不确定为什么会这样,因为我使用的是 var让。请告诉我。
您只调用了一次 new Date
,在构造函数的开头。使用 Date.now
代替(获取数字,避免必须调用 .getTime
),并且不仅在需要分配给 start
时调用它,而且在 .stop
中调用它, 得到 elapsed
.
function Stopwatch() {
var started = false;
var elapsed;
var start;
this.duration = function() {
if (started) {
throw "Stopwatch is still running"
} else {
return (elapsed);
}
}
this.start = function() {
if (started) {
throw "Stopwatch has already started";
} else {
start = Date.now();
started = true;
}
}
this.stop = function() {
if (!started) {
throw "Stopwatch hasn't started";
} else {
elapsed = Date.now() - start;
started = false;
}
}
this.reset = function() {
started = false;
elapsed = 0;
}
}
let sw = new Stopwatch();
sw.start();
setTimeout(() => {
sw.stop();
console.log(sw.duration());
}, 500);
我是 JavaScript 的新手,我制作了一个简单的秒表构造函数:
function Stopwatch() {
var started = false;
var elapsed;
var start;
d = new Date();
this.duration = function() {
if (started) {
throw "Stopwatch is still running"
} else {
return (elapsed);
}
}
this.start = function() {
if (started) {
throw "Stopwatch has already started";
} else {
start = d.getTime();
started = true;
}
}
this.stop = function() {
if (!started) {
throw "Stopwatch hasn't started";
} else {
elapsed = d.getTime() - start;
started = false;
}
}
this.reset = function() {
started = false;
elapsed = 0;
}
}
let sw = new Stopwatch();
sw.start();
setTimeout(function () {
sw.stop();
console.log(sw.duration());
}, 500);
错误的逻辑工作正常,但每当我调用 sw.duration() 时,它总是 returns 零,我不确定为什么会这样,因为我使用的是 var让。请告诉我。
您只调用了一次 new Date
,在构造函数的开头。使用 Date.now
代替(获取数字,避免必须调用 .getTime
),并且不仅在需要分配给 start
时调用它,而且在 .stop
中调用它, 得到 elapsed
.
function Stopwatch() {
var started = false;
var elapsed;
var start;
this.duration = function() {
if (started) {
throw "Stopwatch is still running"
} else {
return (elapsed);
}
}
this.start = function() {
if (started) {
throw "Stopwatch has already started";
} else {
start = Date.now();
started = true;
}
}
this.stop = function() {
if (!started) {
throw "Stopwatch hasn't started";
} else {
elapsed = Date.now() - start;
started = false;
}
}
this.reset = function() {
started = false;
elapsed = 0;
}
}
let sw = new Stopwatch();
sw.start();
setTimeout(() => {
sw.stop();
console.log(sw.duration());
}, 500);