프로토타입과 클래스

서성원·2024년 2월 25일

자바스크립트

목록 보기
2/6
post-thumbnail

객체 생성자

객체생성자는 함수로 새로운 객체를 만들어 그 안에서 값이나 함수를 구현할 수 있게 한다.

new

function Computer(name, type, click) {
	this.name = name;
    this.type = type;
    this.click = click;
    this.hi = function() {
    	console.log(this.click);
    };
}

const myComputer = new Computer('a','b','c');
const notMyComputer = new Computer('d','e','f');

새로운 객체를 만들 때 new 키워드를 앞에 붙이기.
위 코드에서 두 객체의 hi 함수는 수행하는 코드가 같지만 객체가 생성될 때마다 함수도 새로 만들어지므로 this.hi로 설정된다. => 같은 객체 생성자 함수 사용 시 재사용을 가능하게 하는 것이 바로 프로토타입.

프로토타입

function Computer(name, type, click) {
	this.name = name;
    this.type = type;
    this.click = click;
}

Computer.prototype.hi = function() {
	console.log(this.click);
};
Computer.prototype.sharedValue = 1;

const myComputer = new Computer('a','b','c');
const notMyComputer = new Computer('d','e','f');

.prototype.[원하는키] = 코드

객체 생성자 상속받기

새로운 객체 생성자를 만들어 해당 객체 생성자들에서 Computer 기능을 재사용.

function Computer(name, type, click) {
	this.name = name;
    this.type = type;
    this.click = click;
}

Computer.prototype.hi = function() {
	console.log(this.click);
};
Computer.prototype.sharedValue = 1;

function myComputer(type,click) {
	Computer.call(this, 'a', type, click);
}
myComputer.prototype = computer.prototype;

function notMyComputer(type,click) {
	Computer.call(this, 'd', type, click);
}
notMyComputer.prototype = computer.prototype;

const myComputer = new Computer('b','c');
const notMyComputer = new Computer('e','f');

새로 만든 Computer와 notMycomputer 함수에서 computer.call 을 호출. 첫 번째 인자에 this 넣고 이후에 computer 객체 생성자 함수에 필요한 파라미터 넣기. prototype 을 공유해야 하므로 상속받은 객체 생성자 함수 만든 후 prototype 값을 computer.prototype으로 설정.

클래스

ES6 부터 class 무법이 추가되어 좀 더 명확하고 깔끔해짐.

class Computer
	constructor(name, type, click) {
      this.name = name;
      this.type = type;
      this.click = click;
    }
    hi() {
    	console.log(this.click);
    }
}

const myComputer = new Computer('a','b','c');
const notMyComputer = new Computer('d','e','f');

hi 라는 함수를 클래스 내부에서 선언 (메서드) => 자동으로 prototype 으로 등록.

클래스 상속

class Computer
	constructor(name, type, click) {
      this.name = name;
      this.type = type;
      this.click = click;
    }
    hi() {
    	console.log(this.click);
    }
}

class myComputer extends Computer {
	constructor(type, click) {
    	super('a',type,click);
    }
}

class notMyComputer extends Computer {
	constructor(type, click) {
    	super('d',type,click);
    }
}

const myComputer = new Computer('b','c');
const notMyComputer = new Computer('e','f');

상속 시 extends 사용하고 constructor에서 사용하는 super() 함수가 상속받은 클래스의 생성자를 가리킴.

profile
Frontend Developer

0개의 댓글