Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why in javascript apply gives different result than direct call?

I have the following code

var d = new Date();
Object.prototype.toString(d); //outputs  "[object Object]"
Object.prototype.toString.apply(d); //outputs "[object Date]"

Why is this difference and what's going on?

edit:

d.toString() // outputs "Tue Nov 06 2012 ..."

So from where does the Date in "[object Date]" comes from. Is it the native code of the browser that do the trick?

like image 755
suhair Avatar asked Feb 19 '23 14:02

suhair


1 Answers

Object.prototype.toString(d);

converts Object.prototype to string and ignores its argument. In

Object.prototype.ToString.apply(d);

d gets passed as this to the ToString method (as if d.toString() with toString referring to Object.prototype.toString was called), which is what the method respects.

See Function#apply and Object#toString

like image 165
John Dvorak Avatar answered Feb 21 '23 03:02

John Dvorak