js的繼承實現

lonecloud發表於2017-09-24

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);

 

相關文章