【问题标题】:Javascript - recommended way to create an object [closed]Javascript - 推荐的创建对象的方法[关闭]
【发布时间】:2015-02-11 05:27:26
【问题描述】:

看起来有多种方法可以在 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';
}();

有人可以帮我理解以上哪一种是最好的做法吗?

还有我们在什么场景下使用自调用功能?

【问题讨论】:

标签: javascript


【解决方案1】:

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

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

我不推荐自执行匿名函数语法。您应该在其他地方声明该函数(至少用于调试);这至少让您可以选择创建该对象的两个不同实例。

【讨论】:

    【解决方案2】:

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

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

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

    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");
    

    希望这会有所帮助! :)

    【讨论】:

    • 不要引用 W3Schools。阅读this page。有 so many 其他 references 可用,它们要好 100 倍。
    • 会牢记这一点。感谢您的信息!
    猜你喜欢
    • 1970-01-01
    • 2018-04-18
    • 1970-01-01
    • 1970-01-01
    • 2020-11-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-15
    相关资源
    最近更新 更多