当我在命令行上使用node运行此代码时,它只是挂起而不是在打印零后返回。我理解为什么"这个"不增加"年龄",因为函数范围改变了对"这个"的引用。
function Person() {
// The Person() constructor defines `this` as an instance of itself.
this.age = 0;
setInterval(function growUp() {
// In non-strict mode, the growUp() function defines `this`
// as the global object, which is different from the `this`
// defined by the Person() constructor.
this.age++;
}, 1000);
}
var p = new Person();
console.log(p.age);
它挂起是因为setInterval
异步运行,并且也永远运行。Node(和其他命令行程序(通常会缓冲输出,并且不会立即打印它,有时甚至会等到应用程序准备好终止。这可能就是在这种情况下发生的事情。
尝试将setInterval
更改为setTimeout
,看看是否打印了控制台日志。
更新
正如cdbajorin所提到的,setInterval
和setTimeout
都返回一个Timeout
对象(至少在Node上,在浏览器中它们返回数字ID(,您可以将其传递到clearTimeout
中并clearInterval
取消它们。
https://nodejs.org/api/timers.html#timers_setinterval_callback_delay_args
您必须使用 setInterval 清除您已经建立的间隔。在您给出的时间后,它将继续执行。这给了你一个滞后的结果,但这只是一个设定的间隔。 用:
var x = setInterval(function() {
// In non-strict mode, the function defines `this`
// as the global object, which is different from the `this`
// defined by the Person() constructor.
this.age++;
}, 1000);
window.clearInterval(x); // for clearing the interval