Prototype - patrickcole/learning GitHub Wiki
Prototype
A prototype-based language has the notion of a prototypical object, an object used as a template from which to get the initial properties for a new object.
- the
prototype
object is thought of as the blueprint for new objects - using functions to compose new objects, typically have the pattern of capitalizing the object for example:
Person
orMachine
, etc.. - newly created objects not only have the properties and methods that are explicitly declared, but also have methods available implicitly via the object's prototype
- for example:
let user = { first_name: "Patrick", last_name: "Cole" };
// this object has two properties:
// first_name
// last_name
// but it also has properties and methods via the __proto__ property
// methods such as hasOwnProperty, and we can use them
console.log( user.hasOwnProperty("age") ) // => false
Object.create()
- method can be used to create a custom prototype to base an object off of (this is not the same as using Classes)
let DoolittleDog = {
speak: function() {
return `I am a dog`
}
};
function Dog(name, age) {
let dog = Object.create(DoolittleDog);
dog.name = name;
dog.age = age;
return dog;
}
let myDog = new Dog("Rocky", 13);
- the prototype of
Dog
would beDoolittleDog
as it was used to create theDog
object viaObject.create()
Another Example:
// Establish the Person object:
function Person(name) {
this.name = name;
}
// Add the walk method to the Person object:
Person.prototype.walk = function() {
console.log(this.name + ' is walking.');
};
// A new object called Programmer will extend off of Person:
function Programmer(name) {
Person.call(this, name);
this.programmingLanguage = '';
}
// Set the prototype to the prototype of Person using Object.create()
Programmer.prototype = Object.create(Person.prototype);
Programmer.prototype.constructor = Programmer;
// Now the Programmer will have access to the walk() method:
var cory = new Programmer('Cory');
cory.walk(); // Outputs 'Cory is walking.'
Now that the Programmer
object inherits the Person
object, the new object can use the extended properties and methods as well as add its own custom methods:
// Given the previous code example, let's add a writeCode method
// to the Programmer object's prototype:
Programmer.prototype.writeCode = function() {
// notice that the writeCode is referencing the programmingLanguage property
// but it is not set yet:
console.log(this.name + ' is coding in ' + this.programmingLanguage + '.');
};
var cory = new Programmer('Cory');
// now it is set:
cory.programmingLanguage = 'JavaScript';
// run methods:
cory.walk(); // Outputs 'Cory is walking.'
cory.writeCode(); // Outputs 'Cory is coding in JavaScript.'
Prototype Chaining
function Dog(name, age) {
this.name = name;
this.age = age;
}
// chain this onto the prototype:
Dog.prototype.speak = function() {
return `I am a dog`;
}
let john = new Dog("Rocky", 13);