Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does javascript change primitive types when passed into function.apply() or function.call()?

Tags:

javascript

It seems that when using a primitive type (string, number) as the this subject of a function call (as the first argument to either function.call() or function apply()), the primitive type is promoted to its object equivalent (e.g a string turns into a String).

To illustrate:

var f = function(x) { return [typeof(this), typeof(x)]; }  
var obj = '123'  
f.call(obj, obj)  
>>> ["object", "string"]  

That is, "this" becomes an object (it's a String object, I've checked) while the second argument to call becomes the first argument to the function "f", and remains a primitive string.

The objects are both "123", but subtle things don't work (for example, they are equal in terms of "==" but not in terms of "===").

I've noticed this behaviour in both chrome and firefox, so I'm assuming there's a specific reason for it. I've searched, but not found any explanation. I'd appreciate any explanation, hopefully with some sort of link to documentation explaining the rules around this and why it occurs.

like image 379
gfxmonk Avatar asked Feb 04 '23 06:02

gfxmonk


1 Answers

This seems to be the correct behaviour.

http://bclary.com/2004/11/07/#a-15.3.4.4

Function.prototype.call - The called function is passed ToObject(thisArg) as the this value.

ToObject "converts its argument to a value of type Object according to the following":

String - Create a new String object whose [[value]] property is set to the value of the string.

like image 140
James Avatar answered Feb 05 '23 21:02

James