/* StackOverflow needs a console API */ console.log = function(x) { document.write(x + "<br />"); };
B = function() {}
B.prototype = Array.prototype;
var a = new Array();
var b = new B();
a[0] = 1;
b[0] = 1;
console.log(JSON.stringify(a));
console.log(JSON.stringify(b));
JSON stringifies the subclass as an object ( { "0": 1 }
) instead of as an array ( [1]
)`
Is there any way to modify this behaviour?
EDIT
I'm using (non-negotiably) ES5. I've simplified the example slightly. In reality, the subclassing is set up through a function inherit()
which does this:
var inherit = function(base, derived) {
function F() {}
F.prototype = base.prototype;
derived.prototype = new F();
derived.prototype.constructor = derived;
};
As far as I know, you cannot inherit from array. As soon as you create a constructor function, the instances of it will be objects. When you want the functionality of an array, rather create an array and add the methods on it you want. This can be done with a function:
function createExtendedArray () {
var a = [];
a.method1 = function() {};
return a;
}