ES6之函数的双重用途

22 阅读1分钟

ES6之函数的双重用途

function Person(firstName, lastName) { 
    // if (!(this instanceof Person)) {
    //     throw new Error("该函数没有使用new来调用")
    // }
    if (new.target === undefined) {
        throw new Error("该函数没有使用new来调用")
    }
    this.firstName = firstName;
    this.lastName = lastName;
    this.fullName = `${firstName} ${lastName}`;
}
const p1=new Person('李','四')
console.log(p1)
const p2=Person('王','五')
// console.log(p2)
const p3=Person.call(p1,'赵','六')
console.log(p3)

这段代码中前面注释的部分是之前的写法。但这种方法无法判断函数的this指向被更改后的情况。当使用call方法调用时,不会报错。
而使用new.target方法则解决了这个问题。当使用new调用时,会返回调用的函数。当没有使用new调用时,会显示undefined。