【问题标题】:Different typeof 'this' when calling/applying a strict function vs. a non-strict function调用/应用严格函数与非严格函数时的不同类型“this”
【发布时间】:2023-03-24 20:04:01
【问题描述】:

看起来当我在某些非严格函数func 上使用func.call(12) 时,它将使用this = new Number(12) 而不是this = 12(请参阅下面的sn-p)。我注意到因为typeof this 等于'object' 而不是'number'

这是预期的行为吗?有什么办法解决吗?

function a() {
  return this;
}

function b() {
  'use strict';
  return this;
}

const x = a.call(12);
console.log(typeof x);
console.log(x);
console.log(x + 3);

const y = b.call(12);
console.log(typeof y);
console.log(y);
console.log(y + 3);

【问题讨论】:

    标签: javascript node.js


    【解决方案1】:

    这是预期的行为吗?

    是的,这是预期的行为。在草率模式下,this 始终是一个对象 - 将原语转换为它们各自的包装器对象。更糟糕的是,nullundefined 被替换为全局对象。

    有什么办法吗?

    始终使用严格模式。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-11-12
      • 2013-10-08
      • 1970-01-01
      • 1970-01-01
      • 2014-01-02
      • 1970-01-01
      相关资源
      最近更新 更多