我想我刚刚发现了关于JavaScript的一个新的奇怪的事情。
有人知道这到底是怎么回事吗?
let test;
function setProp() {
this.prop = 42;
}
setProp.call(test);
// No error yet?
// So 42 should be saved inside test.prop?
// Though test=undefined?
console.log(test);
try {
console.log(test.prop);
} catch (e) {
console.log(e.message);
}
// -> undefined
// -> Cannot read property 'prop' of undefined
// Ok, indeed
function getProp() {
console.log(this.prop);
}
getProp.call(test);
// -> 42
// Wait, what?
我只是好奇:)
发布于 2021-03-26 23:58:33
在非严格模式下,将undefined作为第一个参数传递给.call()意味着您希望它成为全局对象(如window)。
尝试在顶部使用"use strict";进行测试,看看是否会有所不同。
https://stackoverflow.com/questions/66820254
复制相似问题