자바 풀스택 공부
Day 41_3. [JavaScript] 생성자 함수, 메서드 체이닝
seung_nari
2022. 3. 3. 16:23
Object 생성자 함수
const person = new Object();
const person = {};
위에 있는 코드들은 동일한 코드이다.
생성자 함수(constructor)란 new 연산자와 함께 호출하여 객체(인스턴스)를 생성하는 함수를 말한다.
생성자 함수에 의해 생성된 객체를 인스턴스라고 한다.
const person = new Object();
키워드 객체 = 생성자(인스턴스)
메서드 체이닝
function Rect(x, y) {
this.x = x
this.y = y
this.printArea = function(){
console.log(this.x * this.y)
return this
}
this.setX = function(x){
this.x = x
return this
}
this.setY = function(y){
this.y = y
return this
}
}
var rect = new Rect(6, 9)
console.log(rect.printArea())
rect.setX(5)
console.log(rect.printArea())
rect.setY(5)
console.log(rect.printArea())
new Rect(3, 4).printArea().setX(5).printArea().setY(5).printArea();
this를 return 하는 코드를 사용함으로써 method chaining을 할 수 있습니다.
메서드 체이닝은 연속적인 코드 줄에서 개체의 Method를 반복적으로 호출하는 것을 의미한다.
Method가 객체를 반환하면 그 반환 값(객체)이 또 다른 Method를 호출할 수 있다.
var rect = new Rect(6, 9)
console.log(rect.printArea())
rect.setX(5)
console.log(rect.printArea())
rect.setY(5)
console.log(rect.printArea())
위에 있는 코드를 메서드 체이닝으로 만든 코드가 밑에 있는 코드이다.
new Rect(3, 4).printArea().setX(5).printArea().setY(5).printArea();