var person = {
name: 'Lee',
sayHello: function () {
console.log(`hi! my name is ${this.name}`);
}
};
new
연산자와 함께 Object
생성자 함수를 호출하면 빈 객체를 생성하여 반환
new
연산자와 함께 호출하여 객체(인스턴스)를 생성하는 함수const person = new Object();
person.name = 'Lee';
person.sayHello = function() {
console.log('hi! my name is ' + this.name);
};
console.log(person); // {name: 'Lee', sayHello: f}
person.sayHello(); // hi! my name is Lee
Object
뿐만 아니라 String
, Number
, Boolean
, Function
등 빌트인 생성자 함수를 제공한다.
new
연산자와 함께 호출하면 해당 함수는 생성자 함수로 동작function Circle(radius) {
this.radius = radius;
this.getDiameter = function () {
return 2 * this.radius;
};
}
const circle1 = new Circle(5);
const circle2 = new Circle(10);
console.log(circle1.getDiameter()); // 10
console.log(circle2.getDiameter()); // 20
this
this
가 가리키는 값, 즉 this
바인딩은 함수 호출 방식에 따라 동적으로 결정function Circle(radius) {
// 1. 암묵적으로 빈 객체가 생성되고 this에 바인딩(식별자와 값을 연결하는 과정)
// 2. this에 바인딩되어 있는 리소스를 초기화
this.radius = radius;
this.getDiameter = function () {
return 2 * this.radius;
};
// 3. 완성된 인스턴스가 바인딩된 this를 암묵적으로 반환
// 명시적으로 객체를 반환하면 암묵적인 this반환이 무시
// 명시적으로 원시값을 반환하면 원시값이 무시되고 암묵적으로 this가 반환
}
// 생성자 함수 내부에서 return문을 반드시 생략
[[Call]]
과 [[Construct]]
[[Call]]
이 호출[[Construct]]
이 호출function foo() {}
// 함수는 객체이기 때문에 프로퍼티를 가질 수 있고
foo.prop = 1
// 함수는 객체이기 때문에 메서드를 가질 수 있음
foo.method = function () {
console.log(this.prop)
};
foo.method(); // 10
new
연산자new
연산자와 함께 함수를 호출하면 해당 함수는 생성자 함수로 동작new.target
new
연산자와 함께 생성자 함수로서 호출되면 함수 내부의 new.target
은 함수 자신을 가리킴new
연산자없이 일반 함수로서 호출된 함수 내부의 new.target
은 undefined