function User (name, password) { var self = this instanceof User ? this : new User();
if (name != null) { self.name = name; self.password = password; } return self; }; var obj1 = User("andy",""); var obj2 = new User("andy",""); console.log(obj1.name === obj2.name); // return true;
这样可以防止漏写new,导致的错误。