zoukankan      html  css  js  c++  java
  • js 继承

    以前一直使用的是组合式继承:

     ;(function () {
    
            function father() {
                this.name = "PaPa";
                this.age = 26;
                this.sex = "man";
            }
            father.prototype.say = function (key) {
                console.log(this[key]);
            }
    
            function son(name, age) {
                father.call(this);
                this.age = age;
                this.name = name;
            }
    
            son.prototype = new father();
            son.prototype.constructor = son;
    
            var tempSon = new son("GOUZI", 1);
            tempSon.say("name");//GOUZI
        })()

    昨天看书的时候发现了个问题,这种继承方式会将父类属性继承到子类的原型上,因为继承是依靠原型链的所以就产生了这样一个问题:

    delete tempSon.name;
    tempSon.say("name");//PaPa //tempSon.name已经被删除 读取的是tempSon.prototype.name

    可喜的是 书上也给出了一种结局方案“寄生组合式继承”,名字这么长,这么拉风,其实就是

    让父类的方法继承到子类函数原型上(XXXX.prototype),让父类的属性继承到子类函数对象上(XXXX)。

    不哔哔上代码:

    ;(function () {

    function father() {
    this.name = "PaPa";
    this.age = 26;
    this.sex = "man";
    }

    father.prototype.say = function (key) {
    console.log(this[key]);
    }

    function son(name, age) {
    father.call(this);//call 继承父类的属性
    this.age = age;
    this.name = name;
    }


    ///寄生函数 继承父类的方法
    function inheritFunction(sonClass, fatherClass) {
    var tempObj=Object.create(fatherClass.prototype)
    sonClass.prototype=tempObj;
    tempObj.constructor=sonClass;
    }
    inheritFunction(son,father)

    var tempSon = new son("GOUZI", 1);
    tempSon.say("name");//GOUZI

    delete tempSon.name;
    tempSon.say("name");//undefined

    })()
    函数Object.create()这个方法是出自ES5 低版本浏览器可以这样实现。
     Object.prototype.create = function (o) {
            var F = function () {
            };
            F.prototype = o;
            return new F();
        }

     构造函数记得大写开头,我是小写开头的,这里是个不恰当的地方。

    到这里了,我要试着去看vue的源码啦,拜拜。

  • 相关阅读:
    矩阵快速幂模板
    Kuangbin带你飞 AC自动机
    Kuangbin 带你飞 KMP扩展KMP Manacher
    Kuangbin 带你飞 数位DP题解
    kuangbin 带你飞 数学基础
    Kuangbin 带你飞-基础计算几何专题 题解
    最大团问题
    头文件
    Codeforces 362E Petya and Pipes 费用流建图
    kuangbin带你飞 匹配问题 二分匹配 + 二分图多重匹配 + 二分图最大权匹配 + 一般图匹配带花树
  • 原文地址:https://www.cnblogs.com/dingzhipeng/p/8478638.html
Copyright © 2011-2022 走看看