Esta tradução está incompleta. Por favor, ajude a traduzir este artigo.

A propriedade new.target lets you detect whether a function or constructor was called using the new operator. Em construtores e funções instanciasse com o  operador new , new.target retorna uma referência ao  construtor ou funções. Em chamadas normais de funções , new.target é undefined.

Sintaxe

new.target

Descrição

A sintaxe new.target consiste na palavra- chave "new", o ponto, e o nome da propriedade "target". Normalmente "new." serves as the context for a property access, but here "new." is not really an object. In constructor calls, however, new.target refers to the constructor invoked by new and so "new." becomes a virtual context.

The new.target property is a meta property that is available to all functions. In arrow functions, new.target refers to the new.target of the surrounding function.

Exemplos

new.target em chamadas de Função

Em chamadas normais de função  (as opposed to constructor function calls), new.target is undefined. This lets you detect if a function was called with new as a constructor.

function Foo() {
  if (!new.target) throw 'Foo() must be called with new';
  console.log('Foo instanciado com new');
}

Foo(); // throws "Foo() must be called with new"
new Foo(); // logs "Foo instanciado com new"

new.target em Construtores

In class constructors, new.target refers to the constructor that was directly invoked by new. This is also the case if the constructor is in a parent class and was delegated from a child constructor.

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();}}

Thus from the above example of class C and D, it seems that new.target points to the class Definition of class which is initialized. For example, when D was initialized using new, the class definition of D was printed and similarly in case of c, class C was printed

Especificações

Specification Status Comment
ECMAScript 2015 (6th Edition, ECMA-262)
The definition of 'Built-in Function Objects' in that specification.
Padrão Initial definition.
ECMAScript Latest Draft (ECMA-262)
The definition of 'Built-in Function Objects' in that specification.
Padrão em tempo real  

Compatibilidade com browser

FeatureChromeEdgeFirefoxInternet ExplorerOperaSafari
Basic support46 Yes41 No Yes Yes
FeatureAndroid webviewChrome for AndroidEdge mobileFirefox for AndroidIE mobileOpera AndroidiOS Safari
Basic support4646 Yes41 No Yes Yes

Veja também

Etiquetas do documento e colaboradores

 Colaboradores desta página: LucasGabrielSI
 Última atualização por: LucasGabrielSI,