ES6new.target属性
// 1. ECMAScript 5 中判断构造函数是否通过 new 关键字调用的写法
// function Person (fullName) {
// if (this instanceof Person) {
// this.fullName = fullName;
// } else {
// return new Person(fullName);
// }
// }
// let student = Person('aa')
// 2. ECMASript 6 引入一个 new.target 属性,当我们使用 new 操作符调用构造函数时,new.target 属性的值为构造函数,否则为 undefined
// function Person (fullName) {
// if (typeof new.target !== 'undefined') {
// this.fullName = fullName;
// } else {
// throw new Error('必须通过 new 关键字来调用 Person。');
// }
// }
// let student = new Person('aa');
// console.log(student)
// 3. 除此之外,还可以检查 new.target 是否被某个特定构造函数所有调用。
// 例如,Person 构造函数中的 new.target 属性的值被限定为 Person
// function Person (fullName, age) {
// if (typeof new.target === Person) {
// this.fullName = fullName;
// this.age = age;
// } else {
// throw new Error('必须通过 new 关键字来调用 Person。');
// }
// }
// function Dog (fullName, age) {
// Person.call(this, fullName, age)
// }
// let dog = new Dog('HeHe', 3)
// console.log(dog)
// 4. 不能在函数外部使用 new.target,否则会报错
function Person () {
console.log(new.target)
}
// 下面代码会抛出错误:new.target expression is not allowed here
// console.log(new.target)
let student = new Person('aa')
ES5和ES6语法
// 在 ES 5 中,如果为对象添加方法,必须要通过指定名称并完整定义函数来实现。
let obj = {
fullName: 'ww',
sayName: function () {
return this.fullName;
}
};
// 在 ES 6 中,语法更简洁,取消了冒号和 function 关键字。如下所示:
let obj = {
fullName: 'ww',
sayName () {
return this.fullName;
}
};