Reputation: 60768
From what I understand, the former will:
toString
method on Objectvalue
but with this
bound to value
And value.toString()
will.
toString
method somewhere in value
's prototype chaintoString
on value bound with this
as value via the function invocation patternSo the difference is if there is an overridden toString
method in value... it will use that.
My question is:
Parent
's method and not potentially some overridden by Child
? (In this case Parent = Object, Child = the class value comes from, if we're thinking classically, and method = toString.)Upvotes: 7
Views: 1317
Reputation: 191749
Object.prototype.toString
can be a different method than value.toString()
depending upon what the latter is.
> Object.prototype.toString.apply("asdfasdf")
"[object String]"
> "asdfasdf".toString()
"asdfasdf"
> Object.prototype.toString.apply(new Date)
"[object Date]"
> (new Date).toString()
"Tue Mar 05 2013 20:45:57 GMT-0500 (Eastern Standard Time)"
.prototype[function].apply
(or .call
or .bind
) allow you to change the context of a method even though the context may not have such a method at all.
var o = {};
o.prototype = {x: function () { console.log('x'); }}
var y = {}
o.prototype.x.call(y)
y.x(); //error!
...so that is to say that
Upvotes: 5
Reputation: 69934
Yes, you got this right. I don't usually see people calling Object.prototype.toString
directly like that though (it usually makes some sense to let objects override their toString
method) but its certainly very common and recommended for some other methods like Object.prototype.hasOwnProperty
.
Upvotes: 2
Reputation: 160833
Object.prototype.toString.apple(value)
will let you call on null
, while you use null.toString()
, it will produce an error.
Object.prototype.toString.apply(null);
>"[object Null]"
null.toString();
>TypeError: Cannot call method 'toString' of null
Upvotes: 6