为什么“typeof this”返回“object”?
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 中看到相同的结果,所以我假设它是按照 规范,但是...为什么?规范中的哪里定义了这个?为什么不针对函数呢?
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"
I see the same results in Chrome, Firefox, and Safari, so I assume it's per the spec, but...why? And where in the spec is this defined? And why not for functions?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
正如 ECMA-262 ECMAScript 语言规范第三版中所定义的(参见脚注),它基于 规范(第 15.3.4.4 节):
参数
thisArg
特别注意最后一行。
关键是js原语(
string
,number
,boolean
,null
,undefined) 是不可变的,因此不能将函数附加到它们。因此,
call
函数将原语包装在Object
中,以便可以附加该函数。例如:
不起作用:
起作用:(
脚注)- 正如 patrick dw 在评论中指出的那样,这将会改变在 ECMA-262 ECMAScript 语言规范第五版 当处于严格模式时:
As defined in ECMA-262 ECMAScript Language Specification 3rd edition (see footnote), It's based on the spec (Section 15.3.4.4):
Parameters
thisArg
Note in particular the last line.
The crucial thing is that js primitives (
string
,number
,boolean
,null
,undefined
) are immutable, so a function can not be attached to them. Therefore thecall
function wraps the primitive in anObject
so that the function can be attached.E.g.:
Doesn't work:
Works:
(footnote) - as patrick dw noted in the comments, this will change in ECMA-262 ECMAScript Language Specification 5th edition when in strict mode: