在特定条件下创建对象

Create an object upon a certain condition

如何根据对象内部的特定条件在 Javascript 中创建对象。例如:

function User(email) {

this.email = email;

  this.checkValid = function () {
       // check email if not valid delete the object or return nothing
  }

this.checkValid()

}

var user1 = new User("bob123@aol.com")

function createUser(username, email)
{
    if (email.match(/^[a-z0-9!#$%&\'*+\/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&\'*+\/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/ig))
    {
        window[username] = new User(email);
        return true;
    }
    else
    {
        return null;
    }
}

function User(email) 
{
    this.email = email;
}

if (createUser("user1", "bob123@aol.com"))
{
    document.write("User 1: " + user1.email + "<br />");        
}
if (createUser("user2", "bob123aol.com"))
{
    document.write("User 2: " + user2.email);
}
document.write(window['user1'] + "<br />");
document.write(window['user2']);

这将检查用户是否有有效的电子邮件。如果是这样,则创建一个从 User 构造的全局变量,否则不返回任何内容。您当然可以用任何其他对象替换 window(全局范围)对象。

function User(email) {
    this.email = email;
    this.check();
};

User.prototype.check = function() {
    if (this.email.match(/^[a-z0-9!#$%&\'*+\/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&\'*+\/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/ig)) {
        console.log('Valid email');
    } else {
        console.log('Invalid email');
    }
};


var user1 = new User("bob123@aol.com");

您可以使用 trycatch

function User(email) {
    this.email = email;

    this.checkValid()
}

User.prototype.checkValid = function () {
    var valid = false;
    //or true if valid email

    if(!valid) throw 'Not valid email';
}

try {
    var user1 = new User("bob123@aol.com");
} catch(e) {
    console.log(e);   
}

但在我看来构造函数应该总是创建一个对象,所以我会这样做:

function User(email) {
    this.email = email;
}

User.prototype.isValid = function () {
    if (this.email.match(/^[a-z0-9!#$%&\'*+\/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&\'*+\/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/ig)) {
        return true;
    }
    return false;
}

var user1 = new User("bob123@aol.com");

if(!user1.isValid()){
    user1 = null;
}

if not valid delete the object

不要。更好的是,在尝试创建用户之前测试电子邮件地址是否有效

or return nothing

你真的不能。从构造函数中返回任何内容实际上是不可能的,除非你抛出一个异常。

改为使用额外的工厂函数:

function isValidEmail(str) {
    // http://davidcel.is/blog/2012/09/06/stop-validating-email-addresses-with-regex/
    return /.+@.+\..+/.test(str);
}
function User(email) {
    // possible, but better don't do this:
    // if (!isValidEmail(email)) throw new Error("Tried to create User with invalid email")
    this.email = email;
}

User.prototype.checkValid = function () {
    return isValidEmail(this.email);
};

User.create = function(email) {
    if (isValidEmail(email))
        return new User(email);
    else
        return null;
};

var user1 = User.create("bob123@aol.com")
if (user1)
    this.checkValid() // true