Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a method/function for array/object

Tags:

javascript

This is my first question, so please be gentle.

I'm trying to create an array of objects, where the object includes a method/function to retrieve data.

So eventually I don't want to use getFirstName(arrayName, arrayNumber), but instead use something like

aliens[x].getFirstName;

or

persons.first.getFirstName;

If it's not possible in Javascript, or possible in this manner, please suggest the next best thing.

var persons = [

{
    firstname : "John",
    lastname  : "Doe",
    age       : 50,
    eyecolor  : "blue",
},

{
    firstname : "Jane",
    lastname  : "Siyabonga",
    age       : 39,
    eyecolor  : "brown",
},
]

var aliens = [

{
    firstname : "Bob",
    lastname  : "the Alien",
    age       : 350,
    eyecolor  : "yellow",
},

{
    firstname : "xblanque",
    lastname  : "the Predator",
    age       : 19,
    eyecolor  : "red",
},

]

function getFirstName(arrayName, arrayNumber)
{
    var x = arrayName[arrayNumber].firstname;
    return x;
}

Array.prototype.getLastName=function()
{
    var x = this.lastname;
    return x;
}
like image 504
MisterBrownZA Avatar asked Dec 07 '25 13:12

MisterBrownZA


1 Answers

ECMAscript supports getter and setter methods. In any ES5 compatible implementation, we can use it like

var obj = {
    foo: 42,
    bar: 32,
    get getFoo() {
        return this.foo;
    },
    get sum() {
        return this.foo + this.bar;
    }
};

now we can acces it like

obj.getFoo;  // 42
obj.sum;     // 74

Another way to create those is ES5's Object.defineProperty. For instance:

Object.defineProperty(obj, 'getBar', {
    get: function() {
        return this.bar;
    }
});
like image 141
jAndy Avatar answered Dec 09 '25 01:12

jAndy