如何在JavaScript中构造新对象

时间:2012-10-11 13:00:06

标签: javascript jquery

如何构造已定义对象的新实例?

我的代码与此类似,但this.User = new User();它不起作用。

(function () {

SomeApp = {

    User: {
        FirstName: '',
        LastName: ''

    },

    Users: [],

    init: function () {
        this.User.FirstName = 'Joe';
        this.User.LastName = 'Blogs';

        //add user to list
        var copiedUser = {};
        $.extend(copiedUser, this.User);
        this.Users.push(copiedUser);

        //create new user
        this.User = new User();
        this.User.FirstName = 'Jane';

        //add user to list
        var copiedUser = {};
        $.extend(copiedUser, this.User);
        this.Users.push(copiedUser);
    }
}

SomeApp.init();

})();

1 个答案:

答案 0 :(得分:3)

如果您希望能够使用new创建对象,则可以创建“构造函数”:

function User() {
    this.FirstName = '';
    this.LastName = '';
}

附注:我建议您遵循命名变量的最佳做法。请阅读this guide