Understanding prototype inheritance in Javascript
Object oriented programming (OOP) is commonly used programming paradigm which is based on "Object". And object contains two things, data and methods. Some of most popular OOP languages are C++, Java, Python etc.
But here , we are talking about javascript , So, is Javascript a OOP language ?
YES , Javascript is object oriented programming language, But it is different from other OOP languages like C++, java or python.
Object oriented programming is generally of two type : CLASS based and PROTOTYPE based.
While languages like C++, java, python are class based OOP languages, JavaScript is based on prototype based OOP. And this is why, JavaScript is different from other OOP languages.
In class-based OOP, class is defined before hand and the object is instantiated based on the classe . If two objects Mango and Banana are instantiated from Fruit class, they are fruits inherently and it is sure that you may treat them in the same way; e.g. you can expect the existence of the same behavior such as color, weight or sweetness etc.
In prototype-based OOP, the object is the primary entity. No class exists . The prototype of object is another object to which the object is linked. Every object contains one prototype link and there can be only one. Any new object can be created based on already existing objects chosen as their prototype.
We can call two different objects Mango and Banana a fruit, if the object fruit exists, and both Mango and Banana have fruit as their prototype. The concept of the fruit class doesn't exist separately , but as the equivalence class of the objects sharing the same prototype.
The data and methods of the prototype are delegated to all the objects of the equivalence class defined by it. The data and methods owned individually by the object may not be shared by other objects of the same class; e.g. the attributes sweetness may be unexpectedly absent in Mango . Only single inheritance can be done using the prototype.
Prototype based object oriented programming uses generalized objects, these objects can be cloned and extended.
// Example of true prototypal inheritance style // in JavaScript. var foo = {name: "foo", one: 1, two: 2}; var bar = {two: "two", three: 3}; Object.setPrototypeOf(bar, foo); // foo is now the prototype of bar. bar.one // Resolves to 1. bar.three // Resolves to 3. bar.two; // Resolves to "two" bar.name; // unaffected, resolves to "foo" foo.name; // Resolves to "foo"
No comments:
Post a Comment