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?
As defined in ECMA-262 ECMAScript Language Specification 3rd edition (see footnote), It’s based on the spec (Section 15.3.4.4):
Parameters
thisArgNote 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 thecallfunction wraps the primitive in anObjectso 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: