Available in Chrome 46+ | View on GitHub | Browse Samples
The new.target
value is part of the ES2015 (formerly known as ES6) specification, and can take one of two values:
new.target
is set to a reference to the constructor that
was used when calling new
.
new.target
is set to undefined
.
new.target
is useful for distinguishing at runtime whether code is being executed as
a constructor or as a function. It is also handy as a way to determine the specific subclass
that was used with new
from within a superclass constructor.
'use strict';
class Parent {
constructor() {
// new.target is a constructor reference, and new.target.name is human-friendly name.
/* jshint ignore:start */
ChromeSamples.log('Hello from Parent! ' +
'I was constructed via new ' + new.target.name + '()');
/* jshint ignore:end */
}
}
class FirstChild extends Parent {}
class SecondChild extends Parent {}
function notAConstructor() {
/* jshint ignore:start */
ChromeSamples.log('Hello from notAConstructor()! My new.target is ' +
new.target);
/* jshint ignore:end */
}
// Call all the constructors and the function when the page loads.
new Parent();
new FirstChild();
new SecondChild();
notAConstructor();