Skip to content Skip to sidebar Skip to footer

Javascript - Performing Actions On Array Elements On Creation

I'm trying to create an Object/Class in Javascript that behaves like an Array but with some added functionalities. I've achieved this with these simple lines: var Newclass = Array

Solution 1:

You can make your own derivative of an Array:

function uppercaseStringArray(){
    Array.call(this);
    for(var i = 0; i < arguments.length; i++) this.push(arguments[i]);
}
uppercaseStringArray.prototype = Object.create(Array.prototype);
uppercaseStringArray.prototype.push = function(string){
    Array.prototype.push.call(this, string.toUpperCase());
}

This works exactly like you expect and it still has all the properties normal arrays have:

function uppercaseStringArray(){
    Array.call(this);
    for(var i = 0; i < arguments.length; i++) this.push(arguments[i]);
}
uppercaseStringArray.prototype = Object.create(Array.prototype);
uppercaseStringArray.prototype.push = function(string){
    Array.prototype.push.call(this, string.toUpperCase());
}

var a  = new uppercaseStringArray('tomato', 'apple', 'pear');

console.log(a);

document.write('[' + a.join(', ') + ']');

You could modify the push method to take an unlimited amount of arguments. Please note, however, that this is not a full array, as a[5] = 'thingy' will not modify the length of your array, so be sure to use only methods to add and remove from your array.

This also indentifies itself as both an Array and an uppercaseStringArray using instanceof. And you can add your own methods to the array, like your get_by_id function in its prototype.


Post a Comment for "Javascript - Performing Actions On Array Elements On Creation"