Javascript inheritance question

In his website article on javascript inheritance , Harry Fuecks explains how to implement inheritance as follows:

    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];
    }
};

      

While I understand his code, one question arises: why not remove the for loop and just do this:

 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;
};

      

Thank.

+2


source to share


1 answer


Assigning prototype

one to the function

other will only assign a link to the original prototype

; both will share the same object prototype

. Iterating through prototype

creates a shallow copy of all of its members.



+3


source







All Articles