【前端】两种实现原型继承的方法的对比

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

总结:

方法二更好。

posted @ 2016-02-29 13:07  赵康  阅读(157)  评论(0编辑  收藏  举报