Custom Array Function Using Prototype. New Myarray(1,2,3,4) Not Working
All I need is a custom function to act as an native Array object. When I create an object it should act like same as the new Array(1,2,3,4). It should create an array of elements.
Solution 1:
You can initialize a MyArray
instance by checking the arguments in the constructor and push them if applicable. You may ask yourself if you really need a custom MyArray
constructor to mimic Array
. When you need custom methods, extending the Array.prototype
may be a better option. The enclosed snippet demonstrates this too.
functionMyArray() {
if (arguments.length) {
[].push.apply(this, arguments);
}
}
MyArray.prototype = newArray;
var resultdiv = document.querySelector('#result');
// create new instance of MyArrayvar foo = newMyArray(1, 2, 3, 4, 5, 6);
// downside: you can't do this
foo[foo.length] = 7;
// use MyArray for reportingvar report = newMyArray('<code>foo length: ',
foo.length,
', foo: [',
foo,
']<br><b>@abforce</b>: ',
'foo.hasOwnProperty(\'length\') => ',
foo.hasOwnProperty('length'),
'</code>');
resultdiv.innerHTML = report.join('');
// alternative: adding custom methods to Array.prototypeArray.prototype.lastItem = function () {
returnthis[this.length-1];
};
var bar = [1,2,3,4,5,6];
// now you can
bar[bar.length] = 7;
resultdiv.innerHTML += ['<br><code>bar last item: ',
bar.lastItem(),
'</code>'].join('');
<divid="result"></div>
Solution 2:
you can return an instance of an array in your constructor function
functionMyArray(){
returnnewArray();
}
Note that in this situation, because your constructor function explicitly returns an object, hence the implicit returning of thiswill be ignored.
But in this case the returned object does not follow the MyArray.prototype
, it will be linked to Array.prototype
instead.
Solution 3:
Its working.
functionMyArray() {
var arr = [ ];
arr.push.apply(arr, arguments);
arr.__proto__ = MyArray.prototype;
return arr;
}
MyArray.prototype = newArray;
// Add custom functions here to MyArray.prototype.MyArray.prototype.last = function() {
returnthis[this.length - 1];
};
var sub = newMyArray(1, 2, 3);
console.log(sub);
</script>
Post a Comment for "Custom Array Function Using Prototype. New Myarray(1,2,3,4) Not Working"