javascriptでコンストラクター関数を作成したいと思います。これは、.prototypeプロパティを持ち、newキーワードとともに使用して、プロトタイプチェーンにこのプロパティを持つ新しいオブジェクトを作成できます。また、このオブジェクトで配列をサブクラス化する必要があります。
配列をサブクラス化するオブジェクトを作成できました(必要なすべての機能が機能します)。このオブジェクトを関数として機能させ、コンストラクターとして使用できるようにする方法がわかりません。
SubArray = function() {this.push.apply(this, arguments);};
SubArray.prototype = Object.create(Array.prototype);
SubArray.prototype.constructor = SubArray;
SubArray.prototype.last = function(){return this[this.length -1]};
var arr = new SubArray(0); // [0]
arr.push(1,2,3); // [0,1,2,3]
console.log(arr, arr.length); // [0,1,2,3], 4
arr.length = 2;
console.log(arr, arr.length); // [0,1], 2
console.log(arr.last()); // 2
console.log(arr instanceof Array); // true
console.log(arr instanceof SubArray); // true
arrオブジェクトに特定のキーを追加することで、コンストラクター関数として使用できることを読みました。私はこのようなことをしなければならないと思います。
var arrayFunction = new SubArray(0); // [0]
arrayFunction.prototype = {
constructor: arrayFunction,
//shared functions
};
arrayFunction.call = function(){//this would be the constructor?};
arrayFunction.constructpr = function(){//I remember seeing this as well, but I can't find the original source where I saw this};
これをどのように行うことができるかについての洞察を本当にいただければ幸いです。よろしくお願いします。