new.target
语法
new.target描述
new.target语法由一个关键字"new",一个点,和一个属性名"target"组成。通常"new."的作用是提供属性访问的上下文,但这里"new."其实不是一个真正的对象。不过在构造方法调用中,new.target指向被new调用的构造函数,所以"new."成为了一个虚拟上下文。
new.target属性是一个可以被所有函数访问的元属性。在箭头函数中,new.target指向外围函数的new.target。
示例
函数调用中的 new.target
function Foo() {
  if (!new.target) throw 'Foo() must be called with new';
  console.log('Foo instantiated with new');
}
Foo(); // throws "Foo() must be called with new"
new Foo(); // logs "Foo instantiated with new"构造方法中的 new.target
在类的构造方法中,new.target指向直接被new执行的构造函数。并且当一个父类构造方法在子类构造方法中被调用时,情况与之相同。
class A {
  constructor() {
    console.log(new.target.name);
  }
}
class B extends A { constructor() { super(); } }
var a = new A(); // logs "A"
var b = new B(); // logs "B"
class C { constructor() { console.log(new.target); } }
class D extends C { constructor() { super(); } }
 
var c = new C(); // logs class C{constructor(){console.log(new.target);}}
var d = new D(); // logs class D extends C{constructor(){super();}}从上面类 C 和 D 的例子可以看出来,new.target 指向的是初始化类的类定义。比如当 D 通过 new 初始化的时候,打印出了 D 的类定义,C 的例子与之类似,打印出的是 C 的类定义。
规范
| Specification | Status | Comment | 
|---|---|---|
| ECMAScript 2015 (6th Edition, ECMA-262)The definition of 'Built-in Function Objects' in that specification. | Standard | Initial definition. | 
| ECMAScript Latest Draft (ECMA-262)The definition of 'Built-in Function Objects' in that specification. | Living Standard |  | 
浏览器兼容性
| Feature | Chrome | Edge | Firefox (Gecko) | Internet Explorer | Opera | Safari | 
|---|---|---|---|---|---|---|
| Basic support | 46.0 | (Yes) | 41 (41) | No support | (Yes) | No support | 
| Feature | Android | Android Webview | Edge | Firefox Mobile (Gecko) | IE Mobile | Opera Mobile | Safari Mobile | Chrome for Android | 
|---|---|---|---|---|---|---|---|---|
| Basic support | No support | 46.0 | (Yes) | 41.0 (41) | No support | No support | No support | 46.0 | 
本文档系腾讯云开发者社区成员共同维护,如有问题请联系 cloudcommunity@tencent.com

