当我在命令行上使用节点运行此代码时,它只是挂起而不是在打印零后返回。我理解为什么“this”没有增加“age”,因为函数作用域改变了对“this”的引用。
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
关于javascript - 为什么这段 JavaScript 代码不能干净地退出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45702196/