javascript prototype chain code example
Example 1: prototype inheritance javascript
function Animal (name, energy) {
this.name = name
this.energy = energy
}
Animal.prototype.eat = function (amount) {
console.log(`${this.name} is eating.`)
this.energy += amount
}
Animal.prototype.sleep = function (length) {
console.log(`${this.name} is sleeping.`)
this.energy += length
}
Animal.prototype.play = function (length) {
console.log(`${this.name} is playing.`)
this.energy -= length
}
function Dog (name, energy, breed) {
Animal.call(this, name, energy)
this.breed = breed
}
Dog.prototype = Object.create(Animal.prototype)
Dog.prototype.bark = function () {
console.log('Woof Woof!')
this.energy -= .1
}
const charlie = new Dog('Charlie', 10, 'Goldendoodle')
console.log(charlie.constructor)
Example 2: javascript promise chain
promise
.then(...)
.then(...)
.then(...)
.catch(...)
coinflip(10)
.then(betAgain)
.then(betAgain)
.then(betAgain)
.then(result => {
console.log(`OMG, WE DID THIS! TIME TO TAKE ${result} HOME!`);
})
.catch(handleRejection);
Example 3: prototype chain in javascript
var o = {
a: 2,
m: function() {
return this.a + 1;
}
};
console.log(o.m());
var p = Object.create(o);
p.a = 4;
console.log(p.m());
Example 4: prototype chain in javascript
{
prop: "some value",
__proto__: {
foo: "bar",
constructor: ƒ doSomething(),
__proto__: {
constructor: ƒ Object(),
hasOwnProperty: ƒ hasOwnProperty(),
isPrototypeOf: ƒ isPrototypeOf(),
propertyIsEnumerable: ƒ propertyIsEnumerable(),
toLocaleString: ƒ toLocaleString(),
toString: ƒ toString(),
valueOf: ƒ valueOf()
}
}
}