js的继承实现

1.原型链继承

1.创建父类对象
2.创建子类函数对象
3.将父类的实例对象赋值给子类的原型
4.将子类的原型属性的构造函数设置为 子类本身
    function Person(name) {
        this.name = name;
    }
    Person.prototype.setName = function (name) {
        this.name = name;
    }
    function Student(name, age) {
        this.name = name;
        this.age = age;
    }
    Student.prototype = new Person();
    Student.prototype.constructor = Student;
    Student.prototype.setAge = function (age) {
        this.age = age
    }
    log(new Student("西欧阿米",14));
    log(new Person("你好"))
    log(new Student() instanceof Student)
    log(new Student() instanceof Person)

 2.借用构造函数

    function Person(name,age) {
        this.name=name
        this.age=age
    }
    function Student(name,age,price) {
        Person.call(this,name,age);//借用构造函数模式
        this.price=price;
    }
    var p=new Student("哈哈",12,123000);

 3.原型和构造函数组合模式

    function Person(name,age) {
        this.name=name
        this.age=age
    }
    Person.prototype.setName=function (name) {
        this.name=name;
    }
    function Student(name,age,price) {
        Person.call(this,name,age);//借用构造函数模式
        this.price=price;
    }
    //设置原型
    Student.prototype=new Person();
    //修复构造函数
    Student.prototype.constructor=Student;
    var p=new Student("哈哈",12,123000);
原文地址:https://www.cnblogs.com/lonecloud/p/7587392.html