Javascript—创建对象的推荐方法

Javascript—创建对象的推荐方法,javascript,Javascript,下面似乎有很多方法可以在Javascript中创建对象: var person = { firstName:"John", lastName:"Doe", age:50, eyeColor:"blue" }; function person(){ this.firstName = 'first'; this.lastName = 'last'; this.age = 'age'; this.eyeColor = 'eyecolor

下面似乎有很多方法可以在Javascript中创建对象:

var person = {
    firstName:"John",
    lastName:"Doe",
    age:50,
    eyeColor:"blue"
};

function person(){
    this.firstName = 'first';
    this.lastName = 'last';
    this.age = 'age';
    this.eyeColor = 'eyecolor';
}

person = (function () {
    this.firstName = 'first';
        this.lastName = 'last';
        this.age = 'age';
        this.eyeColor = 'eyecolor';
}();
有人能帮我了解一下上面哪一项是最佳实践吗


还有,在什么情况下我们使用自调用函数?

如果您想获得最大的收益,您可以使用一个函数,它允许您设置“公共”和“私有”变量。例如:

function Person (name, age) {
    var number = (Math.random() * 100) | 0;
    // number is private; there's no way to access it outside
    // of the scope of this function
    var surpriseParty = new Date(Date.now() + number*24*3600*1000);
    // we're throwing you a party within the next 100 days
    this.name = name;    // public
    this.age = age;      // public
    return {
        getName: function () { return name },
        getAge: function () { return name },
        getPartyDate: function () { return surpriseParty }
    }
}
如上面代码中所述,现在只能访问某些变量:

var p = new Person("royhowie", 18);
// p.getName() => "royhowie"
// p.name => "royhowie"
// p.getAge() => 18
// p.age => 18
// p.number => undefined
// p.surpriseParty => undefined
// p.getPartyDate() => date within the next 100 days
然而,事实上,你应该使用最适合你的东西。上述方法是封装数据的简单方法,但如果您希望所有内容都是公共的,请使用普通对象语法:

var p = { name: "royhowie", age: 18, surpriseParty: new Date() };

我不建议使用自动执行的匿名函数语法。您应该在别处声明函数(至少用于调试);这至少为您提供了创建该对象的两个不同实例的选项。

这个问题已经得到了回答,正确地指出没有推荐的创建JavaScript对象的方法。这完全取决于您的用例

根据,有一种创建对象的标准方法:

创建“对象类型”的标准方法是使用对象构造函数。以下是一个例子:

function person(first, last, age, eyecolor) {
    this.firstName = first;
    this.lastName = last;
    this.age = age;
    this.eyeColor = eyecolor;
}
var myFather = new person("John", "Doe", 50, "blue");
var myMother = new person("Sally", "Rally", 48, "green");

希望这有帮助!:)

这取决于您以后想对这些对象执行什么操作,因此实际上没有最佳方法。可能的重复请不要引用。阅读还有其他可用的100倍更好。请记住这一点。谢谢你的信息!