Classes inherits from classes!
// create 'Car' constructor
var Car = function(manufacturer, speed){
this.manufacturer = manufacturer || undefined;
this.speed= speed || 100;
}
Car.prototype= {
drive: function(){
if (this.wings >= 2){
console.log(`Flying wiht ${this.speed} km/h`);
}else{
console.log(`Driving wiht ${this.speed} km/h`);
}
}
}
// create 'Ford' constructor
var Ford = function( speed){
var manufacturer = 'Ford';
// use the parent constructor
Car.apply(this, [manufacturer, speed]);
}
// set the prototype chain
Ford.prototype.__proto__ = Car.prototype;
// create 'ford' object
var ford = new Ford(200);
// create 'theFordOfPesho' object
var theFordOfPesho = new Ford(300);
theFordOfPesho.wings = 2;
ford.drive();
theFordOfPesho.drive();
// create 'car' object
var car = {
manufacturer: undefined,
speed: 100,
drive: function(){
if (this.wings >= 2){
console.log(`Flying wiht ${this.speed} km/h`);
}else{
console.log(`Driving wiht ${this.speed} km/h`);
}
}
}
// create the 'ford' object
var ford = {
// make 'ford' to inherit from 'car'
__proto__ : car,
manufacturer: "Ford",
speed: 200,
}
// create 'theFordOfPesho' object
var theFordOfPesho = {
// make 'theFordOfPesho' to inherit from 'ford'
__proto__ : ford,
wings: 2,
speed: 300,
}
ford.drive();
theFordOfPesho.drive();
__proto__
__proto__
outside of object literals!
// create 'car' object
var car = {
manufacturer: undefined,
speed: 100,
drive: function(){
if (this.wings >= 2){
console.log(`Flying wiht ${this.speed} km/h`);
}else{
console.log(`Driving wiht ${this.speed} km/h`);
}
}
}
// create 'ford' and make it to inherit from 'car'
var ford = Object.create( car, {
manufacturer: {value: "Ford"},
speed: {value: 200},
})
// create 'theFordOfPesho' and make it to inherit from 'ford'
var theFordOfPesho = Object.create(ford, {
wings: {value: 2},
speed: {value: 300},
})
ford.drive();
theFordOfPesho.drive();
__proto__
'Object.create()
aproach, instead of '__proto__
'
// Animal constructor
var Animal = function(food){
this.food = food;
}
Animal.prototype.eat = function(){
console.log(`${this.name} is eating ${this.food}`);
}
// Cat constructor
var Cat = function(name, food){
// reuse the Animal Constructor
Animal.call(this, food);
this.name = name || 'Tom';
}
// Cat objects will inherit from Animal.prototype
Cat.prototype = Object.create(Animal.prototype);
// Cat instance
var tom = new Cat('Tom', 'cheese');
tom.eat();
These slides are based on
customised version of
framework