gpt4 book ai didi

javascript - Function.prototype.call 在严格模式之外改变 this 的类型;为什么?

转载 作者:数据小太阳 更新时间:2023-10-29 05:18:34 26 4
gpt4 key购买 nike

var example = function () {
console.log(typeof this);
return this;
};

在严格模式下:example.call('test') # prints 'string'

否则,example.call('test') # prints 'object'

然而,console.log(example.call('test'))版画 test (如你所料)

为什么 Function.call更改 typeof 'test' === 'string'绑定(bind)到 this里面example

最佳答案

当使用 call() 并将 this 参数设置为一个原始值时,该原始值总是被转换为一个对象,因此您得到的是字符串对象而不是原始字符串

String {0: "t", 1: "e", 2: "s", 3: "t", length: 4, ...

关于 MDNcall() 文档指出

thisArg
The value of this provided for the call to the function.
Note that this may not be the actual value seen by the method: if the method is a function in non-strict mode code, null and undefined will be replaced with the global object, and primitive values will be converted to objects.

所以在非严格模式下,原始字符串值被转换为一个对象,这也在ECMA standard, Annex C中指定。

strict mode restriction and exceptions
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 - Function.prototype.call 在严格模式之外改变 this 的类型;为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32190585/

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