Why does javascript use a different result than a 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 is happening?

edit:

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

So, where does the date in the "Date of Object" come from. Is this the native browser code that does the trick?

+4
source share
3 answers
 Object.prototype.toString(d); 

converts Object.prototype to a string and ignores its argument. IN

 Object.prototype.ToString.apply(d); 

d is passed as this to the ToString method (as if d.toString() had been called with ToString referring to Object.prototype.toString ), which is the method.

See Function#apply and Object#toString

+4
source

The parameter is ignored on the first call. You call the toString method on the Object.prototype object, basically the same way:

 {}.toString(); //outputs "[object Object]" 

In the second call, you call the toString method for Object , but use the Date object as your context. The method returns the type of the object as a string, compares the toString method of the Date object, which instead returns the value of the Date object as a string.

+3
source

Another explanation is that Object.prototype.toString works on the this object. This function is defined by what you call it when you do:

 Object.prototype.toString(); 

The toString this function is an Object.prototype object. When you call it:

 Object.prototype.toString.apply(d); 

its this is the object referenced by d (the Date object).

+1
source

Source: https://habr.com/ru/post/1444261/


All Articles