javascript 有哪些方法能够实现继承?

1.借助构造函数实现继承
// 定义父类
function Parent1 () {
this.name = 'xxx',
this.age = 18
}
// 定义子类
function Child1 () {
//通过call()方法改变Child1的this指向使子类的函数体内执行父级的构造函数从而实现继承效果
Parent1.call(this)
this.address = 'yyy'
}
// 构建子类的实例s1
var s1 = new Child1()
console.log(s1.name) //xxx
缺点:该方法的实力(s1)无法使用父类(Parent1)的原型(prototype)中的属性和方法

2.借助原型链实现继承
function Parent2 () {
this.name = 'xx',
this.age = 19,
this.play = [1,2,3]
}
// 一样在父类添加say方法
Parent2.prototype = {
say () {
console.log('say')
}
}
function Child2 (address) {
this.address = 'yyy'
}
// 让子类的原型直接指向父类实例
Child2.prototype = new Parent2()
// 生成两个子类的实例s2、s3
var s2 = new Child2()
var s3 = new Child2()
// s2实例继承了父类中的name属性
console.log(s2.name) //xx
// s2实例也同样继承了父类原型上的say方法
console.log(s2.say()) //say
缺点:在子类调用构造函数创建对象的时候,无法入参所有的属性值

3.组合继承
function Parent5 () {
this.name = 'xx',
this.age = 20,
this.play = [4,5,6]
}
function Child5 (name,age,address) {
Parent5.call(this,name,age)
this.address = address
}
// 比较关键的一步
Child5.prototype = new Parent5()
var c = new Child5("zhangsan",19,"无锡")


4.实例继承(为父类实例添加新特性,作为子类实例返回)
function Animal (name) {
// 属性
this.name = name || 'Animal';
// 实例方法
this.sleep = function(){
console.log(this.name + '正在睡觉!');
}
}
// 原型方法
Animal.prototype.eat = function(food) {
console.log(this.name + '正在吃:' + food);
};

function Cat(){
var instance = new Animal();
instance.name = name || 'Tom';
return instance;
}
// Test Code
var cat = new Cat();
console.log(cat.name);
console.log(cat.sleep());
console.log(cat instanceof Animal); // true
console.log(cat instanceof Cat); // false

5.拷贝继承
// 定义一个动物类
function Animal (name) {
// 属性
this.name = name || 'Animal';
// 实例方法
this.sleep = function(){
console.log(this.name + '正在睡觉!');
}
}
// 原型方法
Animal.prototype.eat = function(food) {
console.log(this.name + '正在吃:' + food);
};
function Cat(name){
var animal = new Animal();
// 遍历拷贝属性
for(var p in animal){
Cat.prototype[p] = animal[p];
}
Cat.prototype.name = name || 'Tom';
}

// Test Code
var cat = new Cat();
console.log(cat.name);
console.log(cat.sleep());
console.log(cat instanceof Animal); // false
console.log(cat instanceof Cat); // true

原文地址:https://www.cnblogs.com/lishuge/p/13327921.html