• javascript 继承实现


    JavaScript高级程序设计读书笔记

    这本书继承的实现列举了好几种,里面有两种是比较靠谱的。

    1 组合继承

    //父构造函数
    function Super(name) {
        this.name = name;
        this.colors = ['black', 'red'];
    }
    Super.prototype.getName
    = function() { return this.name; }

    //子构造函数
    function Sub(name, age) { Super.call(this, name); this.age = age; }
    //把Sub的原型修改为Super的实例,就能继承Super.prototype中的属性和方法了,
    //这样存在的问题是:把name和colors属性也添加到Sub.prototype中了,这部分对实例是不可见的,
    //因为调用new Sub()生成实例时,会把name和colors添加为实例属性 Sub.prototype
    = new Super(); Sub.prototype.getAge = function(){ return this.age; }
    //前面修改Sub.prototype时,导致
    Sub.prototype.constructor指向了Super,所以要修改回来
    Sub.prototype.constructor = Sub; 
    var ins1 = new Sub('mengxb', 28);

    2 寄生组合式继承

    function Object(o) {
        function F() {};
        F.prototype = o;
        return new F();
    }
    function inheritPrototype(sub, super) {
        var prototype = Object(super.prototype);
        sub.prototype = prototype;
        sub.prototype.construtor = sub;
    }
    
    function Super(name) {
        this.name = name;
        this.colors = ['black', 'red'];
    }
    Super.prototype.getName = function() {
        return this.name;
    }
    function Sub(name, age) {
        Super.call(this, name);
        this.age = age;
    }
    
    inheritPrototype(Sub, Super);
    Sub.prototype.getAge = function(){
        return this.age;
    }
  • 相关阅读:
    Uva11584 Partitioning by Palindromes
    GYM100741 A Queries
    Uva11400 Lighting System Design
    UVA12563 Jin Ge Jin Qu hao
    Uva116 Unidirectional TSP
    HDU2089 不要62
    BZOJ3670: [Noi2014]动物园
    Uva11384 Help is needed for Dexter
    Uva1347 Tour
    BZOJ1924: [Sdoi2010]所驼门王的宝藏
  • 原文地址:https://www.cnblogs.com/mengxiang-1234/p/4685972.html
Copyright © 2020-2023  润新知