Reputation: 1840
I'm confused with Javascript's prototype property. See the below Code.
var s = 12;
var s1 = new String();
console.log(s.constructor); // Outputs: Number() { [native code] }
console.log(s instanceof String); // Outputs: false
console.log(s instanceof Object); // Outputs: false
//console.log(toString() in s);
console.log(s.isPrototypeOf(Object)); // Outputs: false
//console.log(s.prototype.isPrototypeOf(Object));
console.log(s.hasOwnProperty ("toString")); // Outputs: false
console.log(s.toString()); // // Outputs: 12
// My Question is how does toString() function is been called, where does it falls int the prototype chain. Why is it not showing undefined.
console.log(s1.constructor); // Outputs: Number() { [native code] }
console.log(s1 instanceof String); // Outputs: true
I understand that when we create an object by using {} or constructor (new String()) above, it inherits from Object.prototype. And thats why console.log(s1 instanceof String); // Outputs: true
and thus we're able to call toString() on s1. But i'm confused with what happens in the case of var x = "someString" or var x = something.
Thanks for your time.
Upvotes: 0
Views: 36
Reputation: 414046
There's a difference between string primitive values (like "hello world"
) and String objects. Primitive types — strings, numbers, booleans — are not objects.
When primitive values are used like objects, with the .
or []
operators, the runtime implicitly wraps the values in objects via the corresponding constructors (String
, Number
, Boolean
). Primitive values don't have properties, but because of that automatic wrapping you can do things like
var n = "hello world".length;
and it works.
Upvotes: 1