如何为数组/对象创建方法/函数

How to create a method/function for array/object

本文关键字:创建 方法 函数 对象 数组      更新时间:2023-09-26

这是我的第一个问题,请不要客气。

我正在尝试创建一个对象数组,其中对象包括一个方法/函数来检索数据。

最后我不想用getFirstName(arrayName, arrayNumber),而是用

aliens[x].getFirstName;

persons.first.getFirstName;

如果在Javascript中不可能,或者以这种方式可能,请建议下一个最好的方法。

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;
}

ECMAscript支持gettersetter方法。在任何与ES5兼容的实现中,我们都可以像

那样使用它。
var obj = {
    foo: 42,
    bar: 32,
    get getFoo() {
        return this.foo;
    },
    get sum() {
        return this.foo + this.bar;
    }
};

现在我们可以像

那样访问它
obj.getFoo;  // 42
obj.sum;     // 74

另一种创建这些的方法是ES5Object.defineProperty。例如:
Object.defineProperty(obj, 'getBar', {
    get: function() {
        return this.bar;
    }
});

aliens[x].firstname;工作正常。但是,正如@jAndy建议的那样,您可以像使用任何OOP语言一样使用getter和setter。

function Alien( firstname, lastname, age, eyecolor) { // constructor
    // ...
    this.getFirstName = function() {
        return firstname;
    };
}
var aliens = [
    new Alien("Bob", "the Alien", 350, "yellow"),
    new Alien("xblanque", "the Predator", 19, "red")
];
console.log(aliens[0].getFirstName()); // will output "Bob"

还要注意Array.prototype操作:您正在将getLastName方法添加到任何数组中。