Custom array Function using prototype. new MyArray (1,2,3,4) doesn't work

All I need is a custom function that will act like a native Array object. When I create an object, it should act the same way as new Array(1,2,3,4)

. It should create an array of elements.

<script type="text/javascript">

function MyArray(){

}

MyArray.prototype=Array.prototype;

var collection = new MyArray(1, 2, 3, 4);


console.log(collection);


// My code should act like. 

var coll= new Array(1,2,3,4);

console.log(coll);

</script>

      

0


source to share


3 answers


You can initialize an instance MyArray

by inspecting the arguments in the constructor and pushing them if applicable. You may be asking yourself if you really need a custom constructor MyArray

to simulate Array

. If you need special methods, extension Array.prototype

might be the best option. The attached 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>
      

Run code


+3


source


you can return an array instance to your constructor function

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

      



Note that in this situation, since your constructor function is explicitly returning an object, hence the implicit return of this will be ignored .

But in this case, the returned object does not follow MyArray.prototype

, instead it will be associated with Array.prototype

.

0


source


Works.

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>

      

0


source







All Articles