new
를 붙이면 그 리턴 값은 객체가 된다let user = {
name : 'park;,
age : 24,
단일 객체를 만들 때는 리터럴 방식을 사용해 user
라는 객체를 생성,
값만 다른 여러 개의 객체가 필요할 때 일일이 객체를 만들어 줄 필요 없이 생성자 함수를 만들어 주면 됨
function User(name, age) {
//생성자 함수는 보통 첫글자를 대문자로 함.
this.name=name;
this.name=age;
}
const user1 = new User('park',24);
틀을 만들어 준 후 new
를 사용하여 함수의 인스턴스를 생성하게 되면 this로 생성된 객체를 참조
function User(first, last) {
this.firstName = first;
this.lastName = last;
}
User.prototype.getFullName = function () {
return `${this.firstName} ${this.lastName}`;
};
const heropy = new User("Heropy", "Park");
const amy = new User("Amy", "Clarke");
const neo = new User("Neo", "Smith");
console.log(heropy.getFullName());
console.log(amy);
console.log(neo);
생성자를 사용하여 여러개의 객체를 생성하고
프로토타입을 사용하여 속성과 메서드를 생성자에 추가할 수 있다.
this
를 정의this
를 정의const heropy = {
name: "Heropy",
normal: function () {
console.log(this.name);
},
arrow: () => {
console.log(this.name);
},
};
heropy.normal();
heropy.arrow();
>Heropy
>undefined
const amy = {
name: "Amy",
normal: heropy.normal,
arrow: heropy.arrow,
};
amy.normal();
amy.arrow();
>amy
>undefined
화살표함수 사용 시 undefined 가 나오는 이유는 선언된 범위 안에 아무것도 정의가 되어있지 않기 때문
const timer = {
name: "Heropy!!",
timeout: function () {
setTimeout(() => {
console.log(this.name);
}, 2000);
},
};
timer.timeout();
콜백함수 내 범위 안에 선언이 되어있기 때문에 "Heropy" 출력
class User {
constructor(first, last) {
this.firstName = first;
this.lastName = last;
}
getFullName() {
return `${this.firstName} ${this.lastName}`;
}
}
const heropy = new User("Heropy", "Park");
const amy = new User("Amy", "Clarke");
const neo = new User("Neo", "Smith");
console.log(heropy);
console.log(amy.getFullName());
console.log(neo.getFullName());
생성자 메서드는 function 키워드 없이 작성
이 메서드는 this 문맥을 생성하기 때문에 this 속성을 할당함
class Vehicle {
constructor(name, wheel) {
this.name = name;
this.wheel = wheel;
}
}
const myVehicle = new Vehicle("운송수단", 2);
console.log(myVehicle);
class Bicycle extends Vehicle {
constructor(name, wheel) {
super(name, wheel);
}
}
const myBicycle = new Bicycle("삼천리", 2);
const daughtersBicycle = new Bicycle("세발", 3);
console.log(daughtersBicycle);
class Car extends Vehicle {
constructor(name, wheel, license) {
super(name, wheel);
this.license = license;
}
}
const myCar = new Car("벤츠", 4, true);
const daughtersCar = new Car("포르쉐", 4, false);
console.log(myCar);
console.log(daughtersCar);
다음과 같은 결과가 나옴