関数のプロトタイプとして配列を使用して、新しい型が Array から「継承」されるようにし、プロトタイプに新しいメソッドを導入します。
function CustomArray() {}
CustomArray.prototype = [];
// introduce a new method to your custom array type
CustomArray.prototype.total = function() {
return this.reduce(function(ret, el) {
return ret+el;
}, 0);
};
// introduce another new method to your custom array type
CustomArray.prototype.arithmetiMean = function() {
return this.total()/this.length;
};
または、これらのメソッドを新しいインスタンスに導入することもできます。
function CustomArray() {
// introduce a new method to your custom array object
this.total = function() {
return this.reduce(function(ret, el) {
return ret+el;
}, 0);
};
// introduce another new method to your custom array object
this.arithmetiMean = function() {
return this.total()/this.length;
};
}
CustomArray.prototype = [];
var arr = new CustomArray();
arr.push(1); // push is an array-standard method
arr.push(2);
arr.push(3);
arr.push(4);
arr.push(5);
arr.push(6);
arr.push(7);
arr.push(8);
arr.push(9);
arr.push(10);
console.log(arr.arithmetiMean());