1. 程式人生 > >判斷物件的例項

判斷物件的例項

// 方法一: ES3
function Person(name, age) {
    if (!(this instanceof Person)) {
        return new Person(name, age);
    }
    this.name = name;
    this.age = age;
}

// 方法二: ES5
function Person(name, age) {
    var self = this instanceof Person ? this : Object.create(Person.prototype);
    self.name = name;
    self.age = age;
 
    return self;
}

// 方法三:ES6
function Person(name, age) {
    if (!new.target) {
        throw 'Peron must called with new';
    }
    this.name = name;
    this.age = age;
}