new.target sample
This commit is contained in:
Родитель
e98437a4d0
Коммит
8b2c2cbcd4
|
@ -0,0 +1,5 @@
|
||||||
|
new.target Sample
|
||||||
|
===
|
||||||
|
See https://googlechrome.github.io/samples/new-target-es6/index.html for a live demo.
|
||||||
|
|
||||||
|
Learn more at https://www.chromestatus.com/feature/5210159227863040
|
|
@ -0,0 +1,51 @@
|
||||||
|
---
|
||||||
|
feature_name: new.target
|
||||||
|
chrome_version: 46
|
||||||
|
feature_id: 5210159227863040
|
||||||
|
---
|
||||||
|
|
||||||
|
<h3>Background</h3>
|
||||||
|
<p>
|
||||||
|
The <a href="http://www.ecma-international.org/ecma-262/6.0/#sec-meta-properties-runtime-semantics-evaluation"><code>new.target</code></a>
|
||||||
|
value is part of the ES2015 (formerly known as ES6) specification, and can take one of two values:
|
||||||
|
</p>
|
||||||
|
<ul>
|
||||||
|
<li>
|
||||||
|
Inside of a constructor, <code>new.target</code> is set to a reference to the constructor that
|
||||||
|
was used when calling <code>new</code>.
|
||||||
|
</li>
|
||||||
|
<li>
|
||||||
|
Inside of a normal function, <code>new.target</code> is set to <code>undefined</code>.
|
||||||
|
</li>
|
||||||
|
</ul>
|
||||||
|
<p>
|
||||||
|
<code>new.target</code> 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 to the specific subclass
|
||||||
|
that was used with <code>new</code> from within a superclass constructor.
|
||||||
|
</p>
|
||||||
|
|
||||||
|
{% include output_helper.html %}
|
||||||
|
|
||||||
|
{% capture js %}
|
||||||
|
class Parent {
|
||||||
|
constructor() {
|
||||||
|
// new.target is a constructor reference, and new.target.name is human-friendly name.
|
||||||
|
ChromeSamples.log('Hello from Parent! I was constructed via new ' + new.target.name + '()');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class FirstChild extends Parent {}
|
||||||
|
|
||||||
|
class SecondChild extends Parent {}
|
||||||
|
|
||||||
|
function notAConstructor() {
|
||||||
|
ChromeSamples.log('Hello from notAConstructor()! My new.target ' + new.target);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Call all the constructors and the function when the page loads.
|
||||||
|
new Parent();
|
||||||
|
new FirstChild();
|
||||||
|
new SecondChild();
|
||||||
|
notAConstructor();
|
||||||
|
{% endcapture %}
|
||||||
|
{% include js_snippet.html js=js %}
|
Загрузка…
Ссылка в новой задаче