Javascript继承实现问题

时间:2009-10-02 01:09:21

标签: javascript inheritance

在他关于javascript inheritance的站点文章中,Harry Fuecks解释了一种实现继承的方法如下:

    function copyPrototype(descendant, parent) {
    var sConstructor = parent.toString();
    var aMatch = sConstructor.match( /\s*function (.*)\(/ );
    if ( aMatch != null ) { descendant.prototype[aMatch[1]] = parent; }
    for (var m in parent.prototype) {
        descendant.prototype[m] = parent.prototype[m];
    }
};

虽然我理解他的代码,但我想到了一个问题 - 为什么不删除for循环并简单地执行此操作:

 function copyPrototype(descendant, parent) {
    var sConstructor = parent.toString();
    var aMatch = sConstructor.match( /\s*function (.*)\(/ );
    if ( aMatch != null ) { descendant.prototype[aMatch[1]] = parent; }
    descendant.prototype = parent.prototype;
};

感谢。

1 个答案:

答案 0 :(得分:3)

prototypefunction分配给另一个prototype只会分配对原始prototype的引用;两者都将共享相同的 prototype对象。迭代{{1}}会创建其所有成员的浅表副本。

相关问题