Can a custom created object access methods like .toString()
, which is an Object method? How does a custom class connect to an Object?
According to this article:
All objects ultimately have the Object constructor at the end of their prototype chain. This means any methods or properties added to the Object property are automatically available to all objects.
In the previous example, if we called rufus.toString(), javascript would check the rufus object, then the Cat object, then the Pet object. The Pet object’s prototype was created with the Object constructor (using the object literal shortcut) so javascript would then find the toString() method on the Object’s prototype.
Having read through the article, I now understand that in order to inherit from an object, we need to specify in the prototype of the function constructor of an object the object we want to inherit from. But if the prototype property is empty by default, how can an object have the property toString()? I'm confused about this statement.
The Pet object’s prototype was created with the Object constructor (using the object literal shortcut).
Update:
I learned from this source that the prototype property of the constructor function is empty by default. Here's the quote for reference:
First, every JavaScript function has a prototype property (this property is empty by default), and you attach properties and methods on this prototype property when you want to implement inheritance.
So how exactly do we inherit from the javascript Object then?