Even though I have read a lot about it I can’t get my head around the prototype concept.
Why is there a String and String.prototype?
If I have "cat":
- Is that a
Stringor anObject? - Does it inherits all properties/methods from
StringorString.prototype? - Why is there a
StringandString.prototype? - Should I call String the
Stringobject andString.prototypethe String prototype?
Please bring clarity to this.
I’m answering this because there is a lot of misinformation in the subject:
No
"cat"is a primitive String value:I will talk later on about types and primitive values.
Well, when you use the property accessor operator (the dot or the bracket notation), the primitive value is implicitly converted to object, internally, therefore all the methods on
String.prototypeare available, for example:When you access:
Behind the scenes
"cat"is converted to object:That’s why you have access to all the inherited properties on values.
Stringis a constructor function, allows you to create String objects or do type conversion:The
String.prototypeobject, is the object where String object instances inherit from.I know it’s confusing, we have String values and String objects, but most of the time you actually work only with string values, don’t worry for now about String objects.
You should call
String“TheStringconstructor”.“String prototype” is ok.
You should know that “Everything is NOT an object”.
Let’s talk about types, there are five language types specified:
A primitive value is ” a datum that is represented directly at the lowest level of the language implementation”, the simplest piece of information you can have.
The values of the previously described types can be:
null.undefined.0,3.1416,1000, etc.. AlsoNaN, andInfinity.trueandfalse."cat"and"bar".