JS继承方式的总结

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/titoni_yunruohan/article/details/82822541

继承方式一  原型链继承

function parent(){
    this.age = "parent";
}
function child(){
}
//子类想要继承父亲具有父亲的属性name
child.prototype = new parent()
//这样访问child.prototype.age即可得到name
var children = new child()
console.log(children.age)//“parent”

优点

  • 实现了继承

缺点

  • 引用的实例都被所有新建的实例所共享,也就是大家理解的深拷贝,父类容易被改动
  • 子类不能向父类传递任何信息上去

继承方式二  构造函数继承

function parent(sex){
   this.sex = sex;
   this.age = "12";
   this.getAge = function(){
       return this.age;
   }
}
//子类想要继承父类的属性
function child(){
   parent.call(this."female");
}
var children = new child();
console.log(children.age)//12

优点

  • 实现了继承
  • 避免了所有的实例共享引用的实例
  • child可以像parent传值

缺点

  • 方法每次都需要在构造函数中定义,且每次创建一个新的实例都会被创建一遍

继承方式三 组合继承

function parent(){ 
    this.age= "12";
    this.sex = "female";
}
parent.prototype.getAge = function(){
    return this.age;
}
//子类通过上面讲的构造函数继承来实现属性的继承,通过原型链继承方法
function child(){
    parent.call(this);
}
child.prototype = new parent();
var children = new child();
console.log(children.age)//12
console.log(children.getAge())//12

优点

  • 继承方法直接在原型上定义即可,比较常用

缺点

继承方式四  原型式继承

var person = {
    "age":"12",
    "friend":["A","B","C"]
}
var anotherPerson = Object.create(person);
console.log(anotherPerson)
anotherPerson.friend.push("D")//4
console.log(anotherPerson.friend)//["A","B","C","D"]
console.log(person.friend)//["A","B","C","D"]

优点

  • 实现了继承

缺点

  • 和原型链继承一样 共享引用实例

继承方式五 寄生式继承

var person = { "age":"12"}
function anotherPerson(A){
    var clone = Object(A);
    clone.sayHi = function(){
        alert("Hi");
    }
    return clone;
}
//方法每次都会被创建一次
var child = anotherPerson(person);

优点

  • 实现了继承属性的便捷性

缺点

  • 继承方法和构造函数继承一样的麻烦,创建一个实例都需要构建一次

猜你喜欢

转载自blog.csdn.net/titoni_yunruohan/article/details/82822541