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的源码啦,拜拜。

  • 相关阅读:
    What is a .Net Assembly?
    Reading Assembly attributes in VB.NET
    Debugging With Visual Studio 2005
    The Rules for GetHashCode
    The article discusses a couple of new features introduced for assemblies and versioning in Visual Studio 2005.
    Getting a copy of a DLL in the GAC
    Modeling SingleNeuron Dynamics and Computations: A Balance of Detail and Abstraction
    从数学到密码学(八)
    从数学到密码学(十)
    从数学到密码学(三)
  • 原文地址:https://www.cnblogs.com/dingzhipeng/p/8478638.html
Copyright © 2011-2022 走看看