zoukankan      html  css  js  c++  java
  • 【前端】两种实现原型继承的方法的对比

    Preconditions:

    function Student(props) {
        this.name = props.name || 'Unnamed';
    }
    
    Student.prototype.hello = function () {
        alert('Hello, ' + this.name + '!');
    }
    
    function PrimaryStudent(props) {
        // 调用Student构造函数,绑定this变量:
        Student.call(this, props);
        this.grade = props.grade || 1;
    }
    

    方法一:

    function inherits(Child, Parent) {
        Child.prototype = new Parent();
        Child.prototype.constructor = Child;
    }
    
    inherits(PrimaryStudent, Student);
    

    这种情况下PrimaryStudent.prototype.name等于'Unnamed',这条属性显然是多余的。

    方法二:

    function inherits(Child, Parent) {
        var F = function () {};
        F.prototype = Parent.prototype;
        Child.prototype = new F();
        Child.prototype.constructor = Child;
    }
    
    inherits(PrimaryStudent, Student);
    

    这种情况下PrimaryStudent.prototype并没有name这条属性。事实上,PrimaryStudent.prototype上一条冗余属性都没有,非常干净。

    总结:

    方法二更好。

  • 相关阅读:
    Windows 7 SP1无人值守自动应答文件制作
    Ubuntu GNOME单击任务栏图标最小化设置
    NOIP2017题解
    NOIP2017游记
    大模拟1.0
    奇袭
    礼物
    找硬币
    Fiolki
    SQLserver Delete from where 与Oracle delete from where 的差异
  • 原文地址:https://www.cnblogs.com/forzhaokang/p/5227132.html
Copyright © 2011-2022 走看看