gpt4 book ai didi

javascript - 需要澄清严格模式下的 JavaScript 代码行为

转载 作者:行者123 更新时间:2023-12-04 01:01:03 24 4
gpt4 key购买 nike

this关于JavaScript严格模式的MDN文档,在“Semantic differences -> this in function calls”下提到:

When a function was called with call or apply, if the value was a primitive value, this one was boxed into an object (or the global object for undefined and null). In strict mode, the value is passed directly without conversion or replacement.

我需要对此声明进行澄清。当我对此进行测试时,我没有发现任何基于代码模式(严格或草率)的差异。

如果我对声明有误解,请告诉我。

这是我测试的方式:

(function() {
function a() {
console.log(this);
}

function b() {
"use strict";
a.call(2);
}

function c() {
a.call(3);
}

b();
c();
})();

结果:

enter image description here

最佳答案

所描述的行为取决于被调用的函数是否处于严格模式,而不是调用者。

(function() {
function strict() {
"use strict";
console.log(this);
}

function sloppy() {
console.log(this);
}

function b() {
strict.call(2);
}

function c() {
sloppy.call(3);
}

b();
c();
})();

通常您将整个脚本置于严格模式,因此调用者和被调用者之间的区别无关紧要。

关于javascript - 需要澄清严格模式下的 JavaScript 代码行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68288066/

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