原型链继承
function Parent1() {
this.name = 'parent1';
this.play = [1, 2, 3]
}
function Child1() {
this.type = 'child2';
}
Child1.prototype = new Parent1();
console.log(new Child1());
var s1 = new Child1();
var s2 = new Child1();
s1.play.push(4);
console.log(s1.play);
console.log(s2.play);
构造函数继承(借助 call)
function Parent1(){
this.name = 'parent1';
}
Parent1.prototype.getName = function () {
return this.name;
}
function Child1(){
Parent1.call(this);
this.type = 'child1'
}
let child = new Child1();
console.log(child);
console.log(child.getName());
组合继承(原型链继承、构造函数继承)
function Animal(name) {
this.name = name;
}
Animal.prototype.sayName = function() {
console.log('My name is ' + this.name);
}
function Dog(name, breed) {
Animal.call(this, name);
this.breed = breed;
}
let animal = new Animal()
Dog.prototype = animal
Dog.prototype.constructor = Dog
Dog.prototype.bark = function() {
console.log('Woof!');
}
var myDog = new Dog('Max', 'Labrador');
myDog.sayName();
myDog.bark();
寄生式继承
let parent5 = {
name: "parent5",
friends: ["p1", "p2", "p3"],
getName: function() {
return this.name;
}
};
function clone(original) {
let clone = Object.create(original);
clone.getFriends = function() {
return this.friends;
};
return clone;
}
let person5 = clone(parent5);
console.log(person5.getName());
console.log(person5.getFriends());
原型式继承
function Parent(name) {
this.name = name;
}
function content(obj){
function F(){};
F.prototype = obj;
return new F();
}
const obj = {a:1};
const test = Object.create(obj);
var sup = new Person();
var sup1 = content(sup);
console.log(sup1.name);
完美继承(寄生组合)
function Parent(name) {
this.name = name;
}
Parent.prototype.sayHello = function() {
console.log(`Hello, my name is ${this.name}`);
}
function Child(name, age) {
Parent.call(this, name);
this.age = age;
}
Child.prototype = Object.create(Parent.prototype);
Child.prototype.sayAge = function() {
console.log(`I am ${this.age} years old`);
}