Front-End

vsoghlv@naver.com

자바스크립트 생성자함수로 객체만들기

function Person(name, age) {
    console.log(this); //Person{}
    this.name = name;
    this.age = age;
}

const p = new Person("Sun", 28);
console.log(p, p.name, p.age); //Person{} 'Sun' 28

const a = new Person("Sun2", 29);
console.log(a, a.name, a.age); //Person{} 'Sun2' 29

단, 화살표 함수의 경우 this 가리키는 인자가 다르기 때문에 생성자 함수를 만들 수 없다.

const Cat = (name, age) => {
    console.log(this); //Cat is not a constructior
    this.name = name;
    this.age = age;
};

const c = new Cat("고양이", 2); //Cat is not a constructior