About
A prototype-based language has the notion of a prototypical object.
A prototypical object is used as a template from which to get the initial properties for a new object.
Any object can:
- specify its own properties, either when you create it or at run time.
- be associated as the prototype for another object, allowing the second object to share the first object's properties.
Since ECMAScript 2015, a class can be used in place of prototyping for object creation and inheritance
Articles Related
Management
Chain
The father of all prototype is: Object.prototype. See Javascript - Prototype Chain - Hierarchy (Sort of Inheritance)
Get
To get the prototype of an object check the __proto__ attribute.
var element = document.querySelector("body");
console.log(element.__proto__.toString())
Example
Object.create
Basic
var foo = { a: 42 };
// create `bar` and link it to foo
var bar = Object.create( foo );
bar.b = "hello world from bar.b";
console.log( bar.b ); // "hello world"
console.log ("The property 'bar.a' was delegated to the foo prototype. 'bar.a' has the value "+ bar.a ); // 42 <-- delegated to ` foo `
foo.hello = "hello from foo";
console.log ("Attributes added after the initialization are also seen.")
console.log(" The new property 'foo.hello' can be accessed by 'bar': "+bar.hello );
Library with prototype
Constructor and prototype
A prototype can be added to a constructor.
// An object
var person = {
name: "Nicolas",
length: 180
};
// A constructor
function ColoredPerson() {
// Rode piet !
this.color = "red";
}
// Set the prototype to be the person object (dynamic inheritance)
ColoredPerson.prototype = person;
// Create a new object
var coloredPerson = new ColoredPerson();
console.log ( "The object:")
console.log (coloredPerson);
console.log ( "The object prototype:")
console.log (coloredPerson.__proto__);
console.log ( "The object prototype can be directly accessed. Example with the name:")
console.log (coloredPerson.name);
Management
Source of a property (prototype or object)
Prototype inheritance works with a constructor (Always ??)
// An object
var person = {
name: "Nicolas",
length: 180
};
// A constructor
function ColoredPerson() {
// Rode piet !
this.color = "red";
}
// Set the prototype to be the person object (dynamic inheritance)
// All new ColoredPerson must inherit its properties.
ColoredPerson.prototype = person;
// Create a new object
var coloredPerson = new ColoredPerson();
// Loop through the properties
var propSource;
for (var prop in coloredPerson) {
if (coloredPerson.hasOwnProperty(prop)) {
propSource = "object";
} else {
propSource = "prototype";
}
console.log("The property " + prop + " (value:" + coloredPerson[prop] + ") is a property from the " + propSource);
}
Prototype Hierarchy
A function that prints the prototype of the prototype of the .. See Javascript - Prototype Chain - Hierarchy (Sort of Inheritance)