js继承的实现方式

js的面向对象是基于原型的,因此js的对象继承方式也有些特殊,下面我具体谈一下js的几种常用继承方式

1.使用new方法继承

实现原理:在子类的构造函数中调用父类的构造函数。

function Parent(name){
    this.name = name;
    this.age = 40;
    this.sayName = function(){
        console.log(this.name);
    }
    this.sayAge = function(){
        console.log(this.age);
    }
}
function Child(name){
    this.parent = Parent;
    this.parent(name);
    delete this.parent;
    this.saySomething = function(){
        console.log(this.name);
        this.sayAge();
    }
}
var child = new Child('Lee');
child.saySomething();
//Lee
//40

2.使用call方法实现

实现原理:使用call方法改变函数上下文this指向,使之传入具体的函数对象。

function Parent(name){
    this.name = name;
    this.age = 40;
    this.say = function(){
        console.log(this.name + this.age);
    }
}
function Child(name){
    Parent.call(this,name); 
}
var child = new Child('Mike');
child.say();//Mike40

3.使用apply方法实现

实现原理:使用apply方法改变函数上下文this指向,使之传入具体的函数对象。

function Parent(name){
    this.name = name;
    this.age = 40;
    this.say = function(){
        console.log(this.name + this.age);
    }
}
function Child(name){
    Parent.apply(this,[name]);
    //Parent.apply(this,arguments); 效果同上
}
var child = new Child('Wade');
child.say();//wade40

4.使用原型链(prototype)方法实现

实现原理:子类的原型对象指向父类的实例,即重写类的原型。

function Parent(name){
    this.name = name;
    this.say = function(){
        console.log(this.name +' '+ this.age);
    }
}
function Child(age){
    this.age = age;
    this.saySomething = function(){
        console.log(this.name);
    }
}
Child.prototype = new Parent('petter');
var child = new Child(20);
child.say();//petter  20

5.使用混合方式实现

实现原理:使用原型链实现对原型属性和方法的继承,而通过借用构造函数来实现对实例属性的继承。

function Parent(age){
    this.name = 'petter';
    this.age = age;
}
Parent.prototype.say = function(){
    return this.name + ' ' + this.age;
}
function Child(age){
    Parent.call(this,age);
    //Parent.apply(this,[age]);
    this.age = age;
}
Child.prototype = new Parent();
var child = new Child(21);
child.say();//petter  21

6. 寄生组合继承

实现原理:通过寄生方式,砍掉父类的实例属性,这样,在调用两次父类的构造的时候,就不会初始化两次实例方法/属性,避免的混合继承的缺点

function Animal(name){
    this.name = name;
    this.sleep = function(){
        console.log(this.name + 'is sleeping');
    }
}
function Cat(name){
  Animal.call(this);
  this.name = name || 'Tom';
}
(function(){
  // 创建一个没有实例方法的类
  var Super = function(){};
  Super.prototype = Animal.prototype;
  //将实例作为子类的原型
  Cat.prototype = new Super();
})();
// Test Code
var cat = new Cat();
console.log(cat.name);//Tom
console.log(cat.sleep());//Tom is sleeping
console.log(cat instanceof Animal); // true
console.log(cat instanceof Cat); //true
原文地址:https://www.cnblogs.com/nurdun/p/7139632.html