【JS】漫谈原型-3.继承

这里说的继承是采用 call方法+原型改变指向来实现的。

继承在面向对象编程思想里面是非常重要的一块,能够减少代码的编写,方便后期维护,对于前端来说也是减少内存开辟的一个好的方式。不在这里过多的讨论面向对象的思想。先看看怎么实现。

代码:

function Person(name, age) {
        this.name = name;
        this.age = age;
        this.run=function () {
            console.log('run');
        }
    }

    Person.prototype.eat = function () {
        console.log(this.name+' eat')
    }

    function Student(name, age, school) {
        Person.call(this,name, age)
        this.school = school;
    }
     Student.prototype=new Person();

    var s1 = new Student('cong', 26, "qust")
    console.log(s1.name)
    console.log(s1.age)
    console.log(s1.school)
    s1.eat();

运行结果:

现在详细讲讲为啥这么写;

其实 调用call行数和 原型重新指向都能实现继承,不过他们两个方法都有缺点。

比如单独使用call方法:

    function Person(name, age) {
        this.name = name;
        this.age = age;
        this.run=function () {
            console.log(this.name+' run');
        }
    }

    Person.prototype.eat = function () {
        console.log(this.name+' eat')
    }

    function Student(name, age, school) {
        Person.call(this,name, age)
        this.school = school;
    }
     //Student.prototype=new Person();

    var s1 = new Student('cong', 26, "qust")
    console.log(s1.name)
    console.log(s1.age)
    console.log(s1.school)
    s1.run();
    s1.eat();

运行结果

会发现在实例中没有eat方法,我们输出一下s1对象看看结构

发现call方法只是将Person方法中的this变成了s1,之后将这些属性进行赋值了。而Person原型中的方法并没有在s1中体现。

那么单独使用原型重新指向那:

    function Person(name, age) {
        this.name = name;
        this.age = age;
        this.run=function () {
            console.log(this.name+' run');
        }
    }

    Person.prototype.eat = function () {
        console.log(this.name+' eat')
    }

    function Student(name, age, school) {
    //    Person.call(this,name, age)
        this.school = school;
    }
    Student.prototype=new Person();

    var s1 = new Student('cong', 26, "qust")
    console.log(s1.name)
    console.log(s1.age)
    console.log(s1.school)
    s1.run();
    s1.eat();

运行结果:

s1对象结果为

结果倒是有但是没有赋值。

如果这样赋值:Student.prototype=new Person(‘cong’,26);又不符合面向对象思想。

当然也可以之后一个一个属性进行赋值。

所以综上所述才用的组合的方式继承

-----------------------------分割线-----------------------

2021-11-08更新

也可以使用Object.call+Object.assign的方式来实现继承;

这样写的相比较原来的写法有个好处可以保留子类中prototype属性,并且可以实现多继承。

    let Class1=function(){
        this.fun1=function(){}
    }

    Class1.prototype.fun2=function(){}

    let Class2=function(){
        this.fun3=function(){}
        Class1.call(this);
    }

    Class2.prototype.fun4=function(){}

    Object.assign(Class2.prototype,Class1.prototype);

控制台输出

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值