Skip to content Skip to sidebar Skip to footer

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.

function MyArray() { 
  if (arguments.length) {
    [].push.apply(this, arguments);
  }
}
MyArray.prototype = new Array;

var resultdiv = document.querySelector('#result');


// create new instance of MyArray
var foo = new MyArray(1, 2, 3, 4, 5, 6);

// downside: you can't do this
foo[foo.length] = 7;

// use MyArray for reporting
var report = new MyArray('<code>foo length: ', 
                          foo.length,
                         ', foo: [',
                          foo, 
                         ']<br><b>@abforce</b>: ',
                         'foo.hasOwnProperty(\'length\') =&gt; ',
                          foo.hasOwnProperty('length'),
                         '</code>');

resultdiv.innerHTML = report.join('');

// alternative: adding custom methods to Array.prototype
Array.prototype.lastItem = function () {
  return this[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('');
<div id="result"></div>

Solution 2:

you can return an instance of an array in your constructor function

function MyArray(){
    return new Array();
}

Note that in this situation, because your constructor function explicitly returns an object, hence the implicit returning of this will 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.

function MyArray() {
  var arr = [ ];
  arr.push.apply(arr, arguments);
  arr.__proto__ = MyArray.prototype;
  return arr;
}

MyArray.prototype = new Array;

// Add custom functions here to MyArray.prototype.
MyArray.prototype.last = function() {
  return this[this.length - 1];
};

var sub = new MyArray(1, 2, 3);


console.log(sub);
</script>

Post a Comment for "Custom Array Function Using Prototype. New MyArray(1,2,3,4) Not Working"