sorry I really should of asked why there is a differnce ,
`Object.prototype.toString.call(o).slice(x,y);`
and this?
o.toString().slice(x.y);
// why those are different , call should change the 'this' value for the called method
// and toString is already inherited ,
var x = 44 ;
`Object.prototype.toString.call(x)`; //"[object Number]"
x.toString(); // '44'
You're not calling .call
on the method here:
Object.prototype.toString(o).slice(x,y);
Instead, you just call the method (on the prototype object) with o
as an argument.
To get an equivalent method to call to
o.toString().slice(x.y);
(which calls the method on the o
object, with no arguments), you will need to use
o.toString.call(o).slice(x.y);
Why is x.toString()
different from Object.prototype.toString.call(x)
?
Because x = 44
is a number, and when you access x.toString
you get the Number.prototype.toString
method not the Object.prototype.toString
method. You could also write
Number.prototype.toString.call(x)
to get "44"
.
Use second one and check the difference between a class (your first case) and an instance of that class (second case).
http://en.wikipedia.org/wiki/Instance_(computer_science)
Its a general object oriented programming issue common for all languages.
- First is the general definition of the type (without any specific data) - you call it wrong
- The second one is a particular instance with own data (can be multiple)
Anyway:
Object.prototype.toString(o) returns "Object object" so it's not working for you well.
The first one (Object.prototype.toString
) calls the built in or default toString function for objects, the second calls the toString function of o
, which may or may not have been overwritten
var o = {};
o.toString();
// "[object Object]"
o.toString = function(){};
o.toString();
// undefined
Object.prototype.toString.call(o);
// "[object Object]"
With a number, such as 44, the toString function is different from a objects. Calling the toString function of a variable with the value 44, will actually do Number.prototype.toString.call()
. Hence the different output.
a few different types:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/toString
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toString
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/toString
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/toString