gpt4 book ai didi

javascript - 如何在调用函数中设置空上下文?

转载 作者:IT王子 更新时间:2023-10-29 03:03:41 25 4
gpt4 key购买 nike

function test(){         
if(this === null){
console.log("This is null");
}else{
console.log("This is Object");
}
}
test.call(null);
test.call({});

输出:

This is Object.

This is Object.

但我希望输出:

This is Null.

This is Object.

为什么不在上下文中设置 Null?

最佳答案

引自MDN

if the method is a function in non-strict mode, null and undefined will be replaced with the global object and primitive values will be converted to objects.

这解释了为什么在调用 test.call(null); 时会得到一个对象。当此处传递null时,test()中的this将是全局对象Window

对于所需的行为,请使用严格模式。

function test() {
"use strict";
if (this === null) {
console.log("This is null");
} else {
console.log("This is Object");
}
}
test.call(null);
test.call({});

引用自 ES6 规范 strict mode

If this is evaluated within strict mode code, then the this value is not coerced to an object. A this value of null or undefined is not converted to the global object and primitive values are not converted to wrapper objects. The this value passed via a function call (including calls made using Function.prototype.apply and Function.prototype.call) do not coerce the passed this value to an object

关于javascript - 如何在调用函数中设置空上下文?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48257590/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com