gpt4 book ai didi

javascript - 为什么 `typeof this` 返回 "object"?

转载 作者:数据小太阳 更新时间:2023-10-29 04:09:33 26 4
gpt4 key购买 nike

var f = function(o){ return this+":"+o+"::"+(typeof this)+":"+(typeof o) };
f.call( "2", "2" );
// "2:2::object:string"

var f = function(o){ return this+":"+(typeof this)+":"+(typeof o); };
var x = [1,/foo/,"bar",function(){},true,[],{}];
for (var i=0;i<x.length;++i) console.log(f.call(x[i],x[i]));
// "1:object:number"
// "/foo/:object:object"
// "bar:object:string"
// "function () {\n}:function:function"
// "true:object:boolean"
// ":object:object"
// "[object Object]:object:object"

我在 Chrome、Firefox 和 Safari 中看到相同的结果,所以我假设它符合 the spec , 但为什么?这在规范中的何处定义?为什么不是函数?

最佳答案

如 ECMA-262 ECMAScript 语言规范第 3 版(见脚注)中所定义,它基于 the spec (第 15.3.4.4 节):

var result = fun.call(thisArg[, arg1[, arg2[, ...]]]);  

参数

这个参数

Determines the value of this inside fun. If thisArg is null or undefined, this will be the global object. Otherwise, this will be equal to Object(thisArg) (which is thisArg if thisArg is already an object, or a String, Boolean, or Number if thisArg is a primitive value of the corresponding type). Therefore, it is always true that typeof this == "object" when the function executes.

特别注意最后一行。

关键是js原语(string, number, boolean, null, undefined) 是不可变的,因此不能将函数附加到它们。因此,call 函数将原语包装在 Object 中,以便可以附加该函数。

例如:

不起作用:

var test = "string";
//the next 2 lines are invalid, as `test` is a primitive
test.someFun = function () { alert(this); };
test.someFun();

作品:

var test = "string";
//wrap test up to give it a mutable wrapper
var temp = Object(test);
temp.someFun = function () { alert(this); };
temp.someFun();

(脚注)- 作为 patrick dw在评论中指出,这将在 ECMA-262 ECMAScript Language Specification 5th edition 中更改在严格模式下:

From Section 15.3.4.4:

NOTE The thisArg value is passed without modification as the this value. This is a change from Edition 3, where a undefined or null thisArg is replaced with the global object and ToObject is applied to all other values and that result is passed as the this value.

关于javascript - 为什么 `typeof this` 返回 "object"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4390658/

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