0%

es6-new.target

  • new.target 用于检测 方法或构造函数 是否是通过 new 被调用的
  • 通过 new 初始化的 构造函数中,new.target 返回一个指向构造函数的引用
  • 普通函数 则 返回 undefined
1
2
3
4
5
6
7
8
9
10
11
12
class Point {
constructor () {
console.log(new.target); // [class Point]
}
}
const p = new Point()
// console
// class Point {
// constructor () {
// console.log(new.target);
// }
// }
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Parent {
constructor () {
console.log(new.target) // [class Child extends Parent]
if (new.target === Parent) throw new Error('不能实例化')
}
}

class Child extends Parent {
constructor () {
// 继承 构造函数 必须 super
super()
}
}

const p = new Parent() // Error: 不能实例化
const c = new Child() // 只能通过 子类创建实例
// console
// class Child extends Parent {
// constructor () {
// super()
// }
// }
  • 检测 是否通过 new 创建 的实例
    1
    2
    3
    function classCheck (instance, constructor) {
    if (!(instance instanceof constructor)) throw new Error('should exec with new keyword')
    }
-------------本文结束感谢您的阅读-------------