I have a "class" that is essentially a beefed-up Array
:
function NamedArray(name) {
var result = [];
result.name = name;
return result;
};
var cheeses = new NamedArray('Cheeses');
This works great. What doesn't work is adding a prototype for this "class":
NamedArray.prototype = {
nameInAllCaps: function() {
return this.name.toUpperCase();
}
};
cheeses.nameInAllCaps();
=> TypeError: Object #<Object> has no method 'nameInAllCaps'
My first thought was just to mix the "prototype" into the result
Array
:
function NamedArray(name) {
var result = [];
result.name = name;
for (var prop in NamedArray.prototype) {
if (NamedArray.prototype.hasOwnProperty(prop) {
result[prop] = NamedArray.prototype[prop];
}
}
return result;
};
This works, but it causes each instance to have its own copy of the prototype properties. Is there a way to insert NamedArray.prototype into the prototype chain of the result
Array
?