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

  • 相关阅读:
    佛山Uber优步司机奖励政策(2月1日~2月7日)
    长沙Uber优步司机奖励政策(2月1日~2月7日)
    广州Uber优步司机奖励政策(2月1日~2月7日)
    西安Uber优步司机奖励政策(2月1日~2月7日)
    武汉Uber优步司机奖励政策(2月1日~2月7日)
    Apicloud自定义模块
    Android Studio导出jar包
    android studio 、 as 如何导入eclipse项目
    安卓 使用Gradle生成正式签名apk文件
    如何用Android studio生成正式签名的APK文件
  • 原文地址:https://www.cnblogs.com/dingzhipeng/p/8478638.html
Copyright © 2020-2023  润新知