eajni IT 초보사전 💦💦

[JavaScript] 자바스크립트 기초 (클래스)

2023-07-28

Class

  • A JavaScript class is not an object.
  • It is a template for JavaScript objects.
  • Always add a constructor() method.

prototype

Array.prototype
String.prototype
사용 가능한 메서드가 담겨있는 템플릿 객체 (private)

inheritance 관점에서 JS의 유일한 생성자 = Object
객체 –> Prototype –>Prototype –>undefined

  • prototype은 각 속성, 메소드를 별도 설정해야 하는 반면 하나의 그룹으로 동시 설정 가능
class Color {
	constructor(r, g, b, name){ //클래스를 인스턴스화 할때마다 자동 실행
    	this.r = r;	//this => 자동으로 새로운 객체 참조
      	this.g = g;
      	this.b = b;
      	this.name = name;
      
    }
  	rgb(){ //메소드 생성
    	return `rgb(${r},${g}, ${b})`;
    }
  	hex(){
      	const {r,g,b} = this;
    	return `#`+((1<<24)+(r<<16)+(g<<8)+b).toString(16).slice(1));
    }
}

const tomato = new Color(255, 67, 89, 'tomato');
const white = new Color(255, 255, 255, 'white'); 
//new 키워드 사용시 this가 개별 객체를 참조

tomato.hex === white.hex //true 같은 함수, prototype 내에 존재

Comments

Content