[ Web Proxy ]
URL:
Viewing: https://developer.mozilla.org/ru/docs/Web/JavaScript/Reference/Global_Objects/Reflect/construct [Back]  [Original]

Reflect.construct() - JavaScript | MDN

This page was translated from English by the community. Learn more and join the MDN Web Docs community.

View in English Always switch to English

Reflect.construct()

Baseline
Widely available

This feature is well established and works across many devices and browser versions. Its been available across browsers since 2016 ..

Reflect.construct() new operator. new target(...args). .

In this article

function func1(a, b, c) {
  this.sum = a + b + c;
}

const args = [1, 2, 3];
const object1 = new func1(...args);
const object2 = Reflect.construct(func1, args);

console.log(object2.sum);
// Expected output: 6

console.log(object1.sum);
// Expected output: 6

Reflect.construct(target, argumentsList[, newTarget])

target

.

argumentsList

, target .

newTarget

, . new.target . newTarget , target.

target ( newTarget, ), target .

TypeError, target newTarget .

Reflect.construct() ( spread syntax new operator).

js
var obj = new Foo(...args);
var obj = Reflect.construct(Foo, args);

Reflect.construct() Object.create()

Reflect, Object.create().

js
function OneClass() {
  this.name = "one";
}

function OtherClass() {
  this.name = "other";
}

//  :
var obj1 = Reflect.construct(OneClass, args, OtherClass);

// ...  :
var obj2 = Object.create(OtherClass.prototype);
OneClass.apply(obj2, args);

console.log(obj1.name); // 'one'
console.log(obj2.name); // 'one'

console.log(obj1 instanceof OneClass); // false
console.log(obj2 instanceof OneClass); // false

console.log(obj1 instanceof OtherClass); // true
console.log(obj2 instanceof OtherClass); // true

, , . Object.create() Function.prototype.apply(), new.target undefined , new .

, Reflect.construct(), new.target newTarget , target .

js
function OneClass() {
  console.log("OneClass");
  console.log(new.target);
}
function OtherClass() {
  console.log("OtherClass");
  console.log(new.target);
}

var obj1 = Reflect.construct(OneClass, args);
// :
//     OneClass
//     function OneClass { ... }

var obj2 = Reflect.construct(OneClass, args, OtherClass);
// :
//     OneClass
//     function OtherClass { ... }

var obj3 = Object.create(OtherClass.prototype);
OneClass.apply(obj3, args);
// :
//     OneClass
//     undefined

Reflect.construct()

js
var d = Reflect.construct(Date, [1776, 6, 4]);
d instanceof Date; // true
d.getFullYear(); // 1776

Specification
ECMAScript 2027 LanguageSpecification
# sec-reflect.construct


Web Proxy Viewer  |  New URL  |  Original Page