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

标签 javascript

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/

相关文章:

javascript - 壁纸上的可拖动 Sprite

javascript - 旋转 JavaScript 图像

javascript - jQuery 滚动问题与scrollTop

javascript - 使用名称属性在循环中检查第一个单选按钮

javascript - 从 navigator.geolocation.getCurrentPosition 内部调用此函数

javascript - 如何在另一页上显示 map 并全屏查看?

javascript - 在页面刷新时重新连接 SignalR 客户端?

javascript - 序列化 knockout View 模型,想法?

javascript - for循环列表倒计时只出现在第一个

javascript - 元素 $(this) 在 console.log 中输出不同的格式