Markos Evlogimenos
Markos Evlogimenos

Reputation: 718

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?

Upvotes: 0

Views: 79

Answers (1)

pimvdb
pimvdb

Reputation: 154818

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('');
};

Upvotes: 2

Related Questions