6
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.callchangetypeof 'test' === 'string'绑定到thisinside example

4

1 回答 1

6

使用call()并将this参数设置为原始值时,该原始值始终转换为对象,因此您将获得字符串对象而不是原始字符串

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

MDNcall()上的文档指出

thisArg为函数调用提供的
值 注意,这可能不是方法看到的实际值:如果方法是非严格模式代码中的函数,将被替换为全局对象,原始值将转换为对象。this
nullundefined

所以在非严格模式下,原始字符串值被转换为对象,这也在ECMA 标准附件 C中指定

严格模式限制和异常
如果this在严格模式代码中进行评估,则该this值不会被强制转换为对象。or
的 this 值不转换为全局对象,原始值不转换为包装器对象。通过函数调用传递 的and)不会将传递的值强制传递给对象nullundefined
thisFunction.prototype.applyFunction.prototype.callthis

于 2015-08-24T19:58:37.697 回答