Jayden Lin

A Function's prototype: is the object instance that will become the __proto__ for all objects created by using this function as a constructor.

A Object's prototype: is the object instance from which this object is inherited.

1. Shared Instances

2. Prototype Chain 

3. Class-like Inheritance

4. ES 6 Class

var Dog = function (name, color) {
  this.color = color;
  this.name = name;
};
Dog.prototype.age = 5;

var a = new Dog("a","white");
var b = new Dog("b","black");

Dog.prototype.age = 6;

console.log(a.age);
console.log(b.age);

Shared Instances

Dog

Function

Dog

Prototype

age: 5 

a

name: a

color: white 

b

name: b

color: white 

var Dog = function (name, color) {
  this.color = color;
  this.name = name;
};
Dog.prototype.age = 5;

var a = new Dog("a","white");
var b = new Dog("b","black");

Dog.prototype= { age : 6 };

console.log(a.age);
console.log(b.age);

Dog

Function

Dog

Prototype

age: 5 

a

name: a

color: white 

b

name: b

color: white 

 

age: 6

var Dog = function (name, color) {
  this.color = color;
  this.name = name;
};
Dog.prototype.habits = ["run", "eat"];

var a = new Dog("a","white");
var b = new Dog("b","black");

a.habits = ["fight", "bark"];


console.log(a.habits);
console.log(b.habits);

Prototype Chain

Dog

Function

Dog

Prototype

habits: [...] 

a

name: a

color: white 

habits: [...]

b

name: b

color: white 

Class-like Inheritance

function Animal(voice){
  this.voice =voice;
  
}
Animal.prototype.speak=function(){
  console.log(this.voice);
};

function Dog (name, color) {
  Animal.call(this,"hello");
  this.color = color;
  this.name = name;
};

Dog.prototype =  Object.create(Animal.prototype);

var a = new Dog("a","white");
var b = new Dog("b","black");

a.constructor=Dog;
console.log(a.constructor.name);
console.log(a.voice);
a.speak();

ES 6 Class

class Animal{
  constructor(voice){
    this.voice =voice;
  }
  speak(){
    console.log(this.voice);
    //console.log("this.voice");
  }
}


class Dog extends Animal {
  constructor(name, color) {
    super("hello");
    this.color = color;
    this.name = name;
  }
}

var a = new Dog("a","white");
var b = new Dog("b","black");

console.log(a.voice);
a.speak();

JavaScript Prototype

By Jayden Lin

JavaScript Prototype

Introduce the JavaScript Prototype for internal training.

  • 958