20
loading...
This website collects cookies to deliver better user experience
new
keyword. This is a very common pattern in older code bases.new
keyword.animal
and dog
taxonomy, where animal is a prototype of dog.function Animal(name) {
this.name = name;
}
Animal.prototype.eat = function() {
console.log(this.name + ' eats');
};
function Dog(name) {
Animal.call(this, name);
}
// this is a helper function and it could look different in older code bases
function inherit(proto) {
function ChainLink() {}
ChainLink.prototype = proto;
return new ChainLink();
}
Dog.prototype = inherit(Animal.prototype);
Dog.prototype.bark = function() {
console.log(this.name + ' barks');
};
const henry = new Dog('Henry');
henry.bark();
henry.eat();
console.log(Object.getPrototypeOf(henry) === Dog.prototype); //Will be true
console.log(
Object.getPrototypeOf(Dog.prototype) === Animal.prototype,
); //Will be true
new
(Animal and Dog) in PascalCase.eat
method was added to Animal.prototype without ever instantiating an object and assigning it to Animal.prototype. The reason for this is that every function has a pre-existing prototype object. The Dog.prototype
was explicitly assigned and overwrites the previous Dog.prototype object.inherit
function, the Object.create
method could be used.function Dog(name) {
Animal.call(this, name);
}
Dog.prototype = Object.create(Animal.prototype);
Dog.prototype.bark = function() {
console.log(this.name + 'barks');
};
util.inherits
.const util = require('util');
function Dog(name) {
Animal.call(this, name);
}
Dog.prototype.bark = function() {
console.log(this.name + ' barks');
};
util.inherits(Dog.prototype, Animal.prototype);
new
.util.inherits
is a utility function in Node.js to set and overwrite prototypes of objects.