suhair
suhair

Reputation: 10929

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?

Upvotes: 4

Views: 137

Answers (3)

John Dvorak
John Dvorak

Reputation: 27277

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

Upvotes: 4

RobG
RobG

Reputation: 147363

Another explanation is that Object.prototype.toString operates on its this object. A function's this is set by how you call it so when you do:

Object.prototype.toString();

the toString function's this is the Object.prototype object. When you call it as:

Object.prototype.toString.apply(d);

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

Upvotes: 1

Guffa
Guffa

Reputation: 700262

The parameter is ignored in the first call. You are calling the toString method on the Object.prototype object, basically the same as:

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

In the second call you are calling the toString method for Object but applying the Date object as its context. The method returns the type of the object as a string, compared the toString method of the Date object which would instead return the value of the Date object as a string.

Upvotes: 3

Related Questions