Article

Prototypal Inheritance - 1

JavaScript is a prototype based language. In JavaScript, you cannot define classes explicitly. It makes use of prototypes instead of classes to achieve inheritance. It derives its prototype-based inheritance from Self language.

An object can inherit properties from another object, called its prototype. In other words, a prototype is an object from which other objects inherit its properties. Since every object has a prototype, you can imagine a series of objects linked together to form a prototype chain.

The prototypical inheritance mechanism is implicit. When evaluating an expression to retrieve a property, JavaScript determines if the property is defined in the object itself. If it is not found, it looks for the property in the immediate prototype up in the hierarchy (parent scope). This continues until the root prototype is reached. If the property is found, it is returned, else undefined is returned.

You can access the properties defined on the parent scope from the child scope:

childScope.aNum          //returns 322
childScope.anObj.Year   //returns 365

If you access a property that is not defined in the child scope, for example childScope.aFunction(), JavaScript tries to find a property in the parent scope. If it does not find the property in the parent scope also, it'll continue up the prototype chain until it reaches the root scope.

Prototypal Inheritance - 2

childScope.aString  = "Cathie"

Here you are setting a property in the child scope. In this case, the JavaScript does not seek any information from the prototype chain. It simply adds a new aString property to the child scope. A new property defined in a child scope hides the parent scope property with the same name.

childScope.anObj.Year = 366

Since the object 'anObj' is not found in the child scope, JavaScript looks for the object in the parent scope. It finds the 'anObj.Year' property there and updates its value, During the process, it does not create any new object/property in the child scope, it just updates the existing object/property found in the parent scope.

childScope.anObj = {country: 'France', capital: 'Paris' }

A new 'anObj' object is created on the child scope hiding the parent scope property with the same name.