new.target
new.target
new.target
属性允许你检测函数或构造方法是否是通过new运算符被调用的。在通过new运算符被初始化的函数或构造方法中,new.target
返回一个指向构造方法或函数的引用。在普通的函数调用中,new.target
的值是undefined
。
语法
new.target
描述
new.target
语法由一个关键字"new
",一个点,和一个属性名"target"组成。通常"new.
"的
作用是提供属性访问的
上下文,但这里"new.
"其实不是一个真正的
对象。不过在构造方法调用中,new.target
指向被new
调用的
构造函数,所以"new.
"成为了一个虚拟上下文。
new.target属性是一个可以被所有函数访问的元属性。在箭头函数中,new.target指向外围函数的new.target。
示例
函数调用中的 new.target
在普通的函数调用中(和作为构造函数来调用相对),new.target的值是undefined。这使得你可以检测一个函数是否是作为构造函数通过new被调用的。
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 |