js

作用域安全的构造函数

2017-03-02  本文已影响5人  u14e
function Person(name) {
    if (this instanceof Person) {
        this.name = name;
    } else {
        return new Person(name);
    }
}
var person1 = new Person('u14e');
var person2 = Person('u14e');

console.log(person1 instanceof Person);     // true
console.log(person2 instanceof Person);     // true

当被new调用时,设置name属性;不能不是new调用,而是普通函数调用,则以new递归调用自己来为对象创建正确的实例

上一篇 下一篇

猜你喜欢

热点阅读