yuyichao
yuyichao

Reputation: 776

Different behavior for calling function on non-object in javascript

Both firefox's js engine/gjs (spidermonkey) and webkit's jscore seems to have different behavior when calling builtin and normal js functions on non-object.

gjs> toString.call(null)
"[object Null]"
gjs> function cccc() {return toString.call(this);}
gjs> cccc.call(null)
"[object GjsGlobal]"

So if a normal js function is called with non-object, its this is automatically get replaced by the current this, whereas this won't happen for a builtin function.

Is this the standard behavior (according to some specification?) or is it just a implementation dependent behavior? Is the first line always safe to check the type of any value?

THX

Upvotes: 0

Views: 327

Answers (2)

Martijn
Martijn

Reputation: 13632

That behaviour is by design. As noted in the Mozilla documentation:

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 boxed.

Apparently, builtin functions are (treated as) strict mode code. Your own functions are not, unless, of course, you write a strict mode function. :-)

This will be different in ECMAScript 5. From the specification (PDF):

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.

Here’s a more direct link to a non-normative but HTML version of the spec.

Upvotes: 2

micnic
micnic

Reputation: 11255

You can find more information here: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function/call

This is a standard behavior defined by ECMAScript 3rd Edition and yes, this is a method to check the type of any value, usually used to check arrays.

Upvotes: 1

Related Questions