Search code examples
javascriptinheritanceconstructorsuperclass

Trivial Inheritance with JavaScript


function StringStream() {}
StringStream.prototype = new Array();
StringStream.prototype.toString = function(){ return this.join(''); };

Calling new StringStream(1,2,3) gives an empty array

x = new StringStream(1,2,3)

gives

StringStream[0]
__proto__: Array[0]

Can someone please explain why the superclass' (Array) constructor is not called?


Solution

  • Just because StringStream.prototype is an array, the StringStream constructor is not replaced with Array as well.

    You should implement that yourself: http://jsfiddle.net/gBrtf/.

    function StringStream() {
        // push arguments as elements to this instance
        Array.prototype.push.apply(this, arguments);
    }
    
    StringStream.prototype = new Array;
    
    StringStream.prototype.toString = function(){
        return this.join('');
    };