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上一条冗余属性都没有,非常干净。

    总结:

    方法二更好。

  • 相关阅读:
    django--orm操作
    路由
    django ----视图和路由
    DJango 前三天小结
    JQuery----操作01
    前端---JQuery初识
    前端----jsDOM
    前端---js02
    前端-----js
    面向对象
  • 原文地址:https://www.cnblogs.com/forzhaokang/p/5227132.html
Copyright © 2011-2022 走看看