2020-08-11(화) 영어단어 - Javascript Reflection and Reflect API

” JavaScript Reflection and Reflect API “

  • invoke : 언급하다, 적용하다
  • specified : 명시된
  • be used as : -의 대용이 되다, -의 토대로 사용되다

Reflect.apply(target, receiver, args)

예제 소스코드

1
2
3
4
5
6
7
8
9
10
11
12
13
14
/** start of Reflect.apply() */

//let's define a function
function getSum(num1, num2) {

    return `${this.value}${num1 + num2}`;
}

//let's try to invoke the function using Reflect.apply()
const returnedValueOfFunc = Reflect.apply(getSum, { value:'Sum of 1 and 2 is '}, [ 1, 2]);

console.log(returnedValueOfFunc); //output: Sum of 1 and 2 is 3

/** end of Reflect.apply() */

출력결과

1
Sum of 1 and 2 is 3

Reflect.apply

1
const returnedValueOfFunc = Reflect.apply(getSum, { value:'Sum of 1 and 2 is '}, [ 1, 2]);
  • target : first argument which represents the target function

    • getSum : 함수명
  • receiver : second argument which represents the value of this inside the target function

    • { value:’Sum of 1 and 2 is ‘} : 출력할 때 출력내용
  • args : third argument which represents the arguments of the target function in an array object

    • [1, 2] : 함수 안에 들어가는 매개변수

Reflect.construct(target, args, prototype)

예제소스코드

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
/** start of Reflect.constructor */

//let's define a constructor function
function Customer(title,firstName, lastName) {

    this.title = title;
    this.firstName = firstName;
    this.lastName = lastName;

    this.showFullName = function () {

        return `${this.title}. ${lastName}, ${firstName} is from the ${this.country}`;
    }
}
//let's define another constructor set the prototype to add a new property.
function Employee() { }
Employee.prototype.country = 'Philippines';

const myCustomer = Reflect.construct(Customer, ['Dr','Jin Vincent', 'Necesario'],Employee);

console.log(myCustomer.showFullName()); //output: Dr. Necesario,
                                        //Jin Vincent is from the Philippines

/** end of Reflect.constructor */

출력결과

1
Dr. Necesario, Jin Vincent is from the Philippines

Reflect.construct

1
const myCustomer = Reflect.construct(Customer, ['Dr','Jin Vincent', 'Necesario'],Employee);
  • target : the first argument which represents the target constructor
    • Customer : 생성자
  • args : the second argument which represents the arguments of the target constructor. This argument is optional.
    • [‘Dr’,’Jin Vincent’, ‘Necesario’] : 매개변수, 인자값
  • prototype : the third argument which represents another constructor whose prototype will be used as the prototype of the target constructor. This argument is optional.
    • Employee : 다른 생성자(타깃 생성자의 프로토타입을 대신할 수 있는 프로토타입이 있는 다른 생성자)

링크

https://www.codeproject.com/Articles/5275933/JavaScript-Reflection-and-Reflect-API