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

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值