TIL - JS 프로토타입, 클래스 상속

Wooney98·2022년 11월 21일
1

TIL

목록 보기
3/6
post-thumbnail

프로토타입 기반 언어

함수를 prototype의 속성으로 추가

  • 객체 속성으로 함수를 넣을 수 있음
  • 클래스를 생성하면 알아서 prototype 속성이 생성됨
  • class.prototype.aaa = "bbb";
<script>

//생성자이며 클래스 선언
function Product(name, price){
    this.name = name;
    this.price = price;
}

//prototype : 메소드 영역
//멤버 메소드 선언
Product.prototype.print = function(){
    document.write(`${this.name}의 가격은 ${this.price}입니다.<br/>`);
}
var p1 = new Product('바나나',1200);
p1.print();

//배열 선언
var products = [];
products.push(new Product('바나나', 1200));
products.push(new Product('사과', 2000));
products.push(new Product('배', 3000));
products.push(new Product('고구마', 700));
products.push(new Product('감자', 600));
products.push(new Product('수박', 500));

//클래스인 함수 객체 Product에 prototype속성으로 추가, 자바의 static
// 자바스크립트같은 경우 모든 것이 객체이므로, 해당 속성에 함수를 넣어도 되고,
// 배열을 넣어도되고, 맵을 넣어도 됨.
Product.prototype.aaa = "bbb";

for(let i in products){
    products[i].print();
    console.log(products[i].aaa);
}
</script>

클래스인 함수 객체 Product에 prototype 생성됨
그러므로 Product.prototype.attributebyMe 의 참조 방식으로 속성 추가 가능
자바스크립트같은 경우 모든 것이 객체이므로, 해당 속성에 함수를 넣어도 되고,
배열을 넣어도 되고, 맵을 넣어도 되고 전부가능

프로토타입 방식

첨언 : https://developer.mozilla.org/ko/docs/Web/JavaScript/Inheritance_and_the_prototype_chain

  • 프로토타입 체인을 이용한 속성상속
    • 자바스크립트 객체는 속성을 저장하는 동적인 "가방"과 (자기만의 속성이라고 부른다) 프로토타입 객체에 대한 링크를 가진다.
    • 객체의 어떤 속성에 접근하려할 때 그 객체 자체 속성 뿐만 아니라 객체의 프로토타입, 그 프로토타입의 프로토타입 등 프로토타입 체인의 종단에 이를 때까지 그 속성을 탐색한다.

// objectA라는 객체가 있고, 속성 'a' 와 'b'를 갖고 있다고 하자.
let funcA = function () {
    this.a = 1;
    this.b = 2;
}
let objectA = new f(); // {a: 1, b: 2}

아래와 같은 방식으로 funcA함수에 프로퍼티 속성 추가

// funcA 함수의 prototype 속성 값들을 추가 하자.
funcA.prototype.b = 3;
funcA.prototype.c = 4;

✋해당 코드는 prototype chain 을망가뜨리기 때문에 딕셔너리 형식으로 속성 추가하지말것

funcA.prototype = {uniquename: 'uniqueName' , uniqueNumber : 10202.569}

  • 객체를 복사하여 프로토타입을 상속하는 방식
<script>
// Product 클래스를 상속하는 Car 클래스
function Product(name, price){
	this.name = name;
	this.price = price;
  
}
Product.prototype.print = function(){
	document.write(`${this.name}의 가격은 ${this.price}입니다.`);
}

function Car(name, price, company){
	this.company = company;
}

// 전통적인 방식의 Javascript 상속
// ES6 버전 이후에는  class와 extends 키워드가 추가 되었다.
// class 키워드를 사용 해도 최종적으로 protype방식으로 바뀜.
Car.prototype = new Product();
Car.constructor = Car;

var car = new Car("그랜저", 5000만원, 현대)
car.print();
//car클래스에는 print()메소드가 없지만, prototype방식의 상속을 통하여
//부모 클래스인 Product에 있는 print 함수를 사용할 수 있음

</script>

클래스 방식

  • 메소드 상속
    • 자바스크립트는 객체의 속성으로 함수를 지정할 수 있고 속성 값을 사용하듯 쓸 수 있다.
    • 메소드 오버라이딩
<script>
class Product{
	print(){
		console.log("Product Class");
	}
}

class Car extends Product {
}

let car = new Car();
car.print();
</script>

<script>
class Product{
		print(){
	console.log("Product Class");
	}
}

class Car extends Product {
	print(){
		console.log("Car class")
	}
}

let car = new Car();
car.print();
</script>

  • 동적바인딩
<script>
class Product{
	constructor(name, price){
		this.name = name;
		this.price = price;
	}
	print(){
		console.log("Product Class");
		document.write(`${this.name}의 가격은 ${this.price}원입니다.<br/>`)
		document.write(`제조사 : ${this.company}`)
	}
}

class Car extends Product {
	constructor(name, price, company){
		super(name, price);
		this.company = company;
	}
}

let car = new Car('소나타', 3500, '현대');
car.print();
</script>

  • 오버라이딩(1)
<script>
class Product{
	constructor(name, price){
		this.name = name;
		this.price = price;
	}
	print(){
		console.log("Product Class");
		document.write(`${this.name}의 가격은 ${this.price}원입니다.<br/>`)
	}
}

class Car extends Product {
	constructor(name, price, company){
		super(name, price);
		this.company = company;
	}
	print(){
		super.print();
		document.write(`제조사 : ${this.company}<br/>`);
	}
}

let car = new Car('소나타', 3500, '현대');
car.print();
</script>

  • 오버라이딩(2)
<script>
class Product {
	constructor(name, price) {
		this.name = name;
		this.price = price;
	}
	//aaa(){}
	print() {
		console.log('열심히 해서 개발자로 먹고 살자!');
		document.write(`${this.name}의 가격은 ${this.price}원입니다.`);
		this.aaa();
	}
}

class Car extends Product {
	constructor(name, price, company){
		super(name, price);
		this.company = company;
	}
	aaa() {
		document.write("<p>Car의 aaa 메소드</p>");
	}
	print() {
		super.print();
		document.write(`<p>제조사 : ${this.company}</p>`);
	}
}

let car = new Car('SONATA',3500,'HYUNDAI');
car.print();
</script>

profile
👨Education Computer Engineering 🎓Expected Graduation: February 2023 📞Contact info thstjddn77@gmail.com

0개의 댓글