James Franco James Franco - 6 months ago 9
Javascript Question

How do custom objects inherit from Javascript Object

How does a custom created object have access to methods such as

.toString()

method which is an Object method. How is a custom class linked to an Object

This article states


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


Now after reading through the article I understand that in order to inherit from an object we have to specify in the prototype of the function constructor of an object the object we would like to inherit from. Now I read that by default the prototype property is empty.Then how can an object have the property toString() ? I dont understand the statement


The Pet object’s prototype was created with the Object constructor
(using the object literal shortcut)


Update:

I read that the prototype property of the constructor function is empty by default. I read that here I have pasted the quote here


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.


How do we inherit from the javascript Object then ?

Answer

All objects inherit the properties of Object via prototypal inheritance. If you do :

var b = {};
console.log(b.__proto__)

you can see all the properties inherited from Object.

So, what happens is that when you do b.toString(), it will look for the toString() function on b, then it will keep going up the prototype chain and ultimately reach Object which has this function.

EDIT:

Function Constructors vs Objects:

Just to clarify, a function constructor defined like:

var a = function() {
   this.b = "b";
   this.c = "c";
}

has its prototype set to function. This can be verified by doing console.log(a).

However, we use a to create new Objects like this:

var d = new a();

And these objects have their prototype set to Object which, again, can be verified by doing console.log(d).

More details here.