Function.prototype.call 在严格模式之外改变 this 的类型;为什么?
Function.prototype.call alters typeof this, outside strict mode; why?
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'
绑定到example
内的this
?
当使用 call()
并将 this
参数设置为原始值时,该原始值总是转换为对象,因此您得到的是字符串对象而不是原始字符串
String {0: "t", 1: "e", 2: "s", 3: "t", length: 4, ...
MDN 上 call()
的文档指出
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
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'
绑定到example
内的this
?
当使用 call()
并将 this
参数设置为原始值时,该原始值总是转换为对象,因此您得到的是字符串对象而不是原始字符串
String {0: "t", 1: "e", 2: "s", 3: "t", length: 4, ...
MDN 上 call()
的文档指出
thisArg
The value ofthis
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
andundefined
will be replaced with the global object, and primitive values will be converted to objects.
所以在非严格模式下原始字符串值被转换为一个对象,这也在ECMA standard, Annex C
中指定strict mode restriction and exceptions
Ifthis
is evaluated within strict mode code, then thethis
value is not coerced to an object.
A this value ofnull
orundefined
is not converted to the global object and primitive values are not converted to wrapper objects.
Thethis
value passed via a function call (including calls made usingFunction.prototype.apply
andFunction.prototype.call
) do not coerce the passedthis
value to an object