Reflect.construct()
Baseline
Widely available
This feature is well established and works across many devices and browser versions. Itโs been available across browsers since โจ2016๋ 9์โฉ.
Reflect.construct()
์ ์ ๋ฉ์๋๋ new
์ฐ์ฐ์์ฒ๋ผ ๋์ํ๋ ํจ์์
๋๋ค. new target(...args)
๋ฅผ ํธ์ถํ๋ ๊ฒ๊ณผ ๊ฐ์ต๋๋ค. ์ถ๊ฐ ๊ธฐ๋ฅ์ผ๋ก ๋ค๋ฅธ ํ๋กํ ํ์
์ ์ง์ ํ ์๋ ์์ต๋๋ค.
์๋ํด ๋ณด๊ธฐ
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
Optional-
ํ๋กํ ํ์ ์ผ๋ก ์ฌ์ฉํ ์์ฑ์.
new.target
์ฐ์ฐ์๋ ํ์ธํ์ธ์.newTarget
์ด ์ฃผ์ด์ง์ง ์์์ ๋target
์ ์ฌ์ฉํฉ๋๋ค.
๋ฐํ ๊ฐ
target
์ ์์ฑ์๋ก ํ๊ณ ์ฃผ์ด์ง ๋งค๊ฐ๋ณ์๋ฅผ ์ ๋ฌํด ์์ฑํ target
(๋๋, ์ง์ ํ๋ค๋ฉด newTarget
)์ ์๋ก์ด ์ธ์คํด์ค.
์์ธ
target
๋๋ newTarget
์ด ์์ฑ์๊ฐ ์๋๋ฉด TypeError
.
์ค๋ช
Reflect.construct()
๋ ์์ฑ์๋ฅผ ๊ฐ๋ณ ๊ธธ์ด์ ๋งค๊ฐ๋ณ์๋ก ํธ์ถํ ์ ์์ต๋๋ค. (new
์ฐ์ฐ์์ ์ ๊ฐ ๊ตฌ๋ฌธ์ ์ฌ์ฉํด๋ ๊ฐ๋ฅํฉ๋๋ค)
var obj = new Foo(...args);
var obj = Reflect.construct(Foo, args);
Reflect.construct()
vs Object.create()
Reflect
์ ๋์
์ด์ ์๋ ์์์ ์์ฑ์์ ํ๋กํ ํ์
์ Object.create()
๋ฅผ ์ฌ์ฉํด ๊ฐ์ฒด๋ฅผ ์์ฑํ ์ ์์์ต๋๋ค.
function OneClass() {
this.name = "one";
}
function OtherClass() {
this.name = "other";
}
// Calling this:
var obj1 = Reflect.construct(OneClass, args, OtherClass);
// ...has the same result as this:
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
ํค์๋๊ฐ ๊ด์ฌํ์ง ์์ผ๋ฏ๋ก new.target
์ฐ์ฐ์๊ฐ undefined
๋ฅผ ๊ฐ๋ฆฌํต๋๋ค.
๋ฐ๋ฉด Reflect.construct()
๋ฅผ ํธ์ถํ๋ฉด, newTarget
์ด ์กด์ฌํ๋ฉด new.target
์ฐ์ฐ์๊ฐ newTarget
์, ์๋๋ฉด target
์ ๊ฐ๋ฆฌํต๋๋ค.
function OneClass() {
console.log("OneClass");
console.log(new.target);
}
function OtherClass() {
console.log("OtherClass");
console.log(new.target);
}
var obj1 = Reflect.construct(OneClass, args);
// Output:
// OneClass
// function OneClass { ... }
var obj2 = Reflect.construct(OneClass, args, OtherClass);
// Output:
// OneClass
// function OtherClass { ... }
var obj3 = Object.create(OtherClass.prototype);
OneClass.apply(obj3, args);
// Output:
// OneClass
// undefined
์์
Reflect.construct()
์ฌ์ฉํ๊ธฐ
var d = Reflect.construct(Date, [1776, 6, 4]);
d instanceof Date; // true
d.getFullYear(); // 1776
๋ช ์ธ
Specification |
---|
ECMAScriptยฎ 2026 Language Specification # sec-reflect.construct |
๋ธ๋ผ์ฐ์ ํธํ์ฑ
Loadingโฆ