-
자바스크립트 - 클래스프로그래밍/JavaScript 자바스크립트 2021. 9. 30.반응형<!DOCTYPE html><html><head><meta charset="UTF-8"><title>Insert title here</title><link rel="icon" href="data:;base64,iVBORw0KGgo="><script type="text/javascript">// 클래스class User {// 생성자 : 생성자는 클래스 안에서 반드시 constructor 라는 이름으로 정의 한다.constructor({name, age}) {this.name = name;this.age = age;}// 메소드를 만드는 문법 그대로 사용하면 메소드가 자동으로 User.prototype 에 저장된다.msg() {return '안녕하세요. 제 이름은 ' + this.name + '입니다';}}const obj = new User({name:'호호호', age:20});console.log( obj.msg() );console.log( typeof User ); // functionconsole.log( typeof User.prototype.constructor ); // functionconsole.log( typeof User.prototype.msg ); // functionconsole.log( obj instanceof User ); // true</script></head><body><h3>클래스</h3></body></html>
자바처럼 비슷하게 클래스 생성이 가능한데
주의할 점은 자바스크립트에서 생성자는 무조건 constructor를 통해서 생성 해야함.
<!DOCTYPE html><html><head><meta charset="UTF-8"><title>Insert title here</title><link rel="icon" href="data:;base64,iVBORw0KGgo="><script type="text/javascript">class User {add(x, y) {return x+y;}subtract(x, y) {return x-y;}}const obj = new User();console.log( obj.add(10, 5) );</script></head><body><h3>클래스</h3></body></html>자바와 유사한 모습
<!DOCTYPE html><html><head><meta charset="UTF-8"><title>Insert title here</title><link rel="icon" href="data:;base64,iVBORw0KGgo="><script type="text/javascript">const methodName = 'sayName';class User {constructor(name, age) {this.name = name;this.age = age;}// 임의의 표현식을 []로 둘러 쌓아 메소드 이름으로 사용[methodName]() {return `안녕 나는 ${this.name} 이야 .`;}}const obj = new User('나나나', 10);console.log( obj.sayName() );</script></head><body><h3>클래스</h3></body></html>대괄호 [] 안에 함수 이름을 넣어서 그걸 메소드 이름으로 사용하는게 있는데
잘 안쓰인다.
<!DOCTYPE html><html><head><meta charset="UTF-8"><title>Insert title here</title><link rel="icon" href="data:;base64,iVBORw0KGgo="><script type="text/javascript">class User {constructor() {this._name = "";}get name() {return this._name;}set name(newName) {this._name = newName;}}const obj = new User();obj.name = '홍길동';console.log( obj.name );</script></head><body><h3>클래스 - getter, setter </h3></body></html>자바의 게터 세터 getter / setter 와 비슷한 내용
_언더바는 그냥 변수 이름이다.
naem의 메소드가 2개있는데 인자가 있냐 없냐에 따라서 기능이 다른것.
obj.name = '홍길동' 이건 클래스 User의 객체 obj를 통해서 name(newName)을 호출한 것이랑 동일
<!DOCTYPE html><html><head><meta charset="UTF-8"><title>Insert title here</title><link rel="icon" href="data:;base64,iVBORw0KGgo="><script type="text/javascript">class Rect {constructor(height, width) {this.height = height;this.width = width;}// getterget area() {return this.calc();}// 메소드calc() {return this.height * this.width;}}var obj = new Rect(10, 5);console.log( obj.area );console.log( obj.calc() );</script></head><body><h3>클래스</h3></body></html>게터 세터 응용한 모습
<!DOCTYPE html><html><head><meta charset="UTF-8"><title>Insert title here</title><link rel="icon" href="data:;base64,iVBORw0KGgo="><script type="text/javascript">/*class Rect {// 생성자constructor(h, w) {this.height = h;this.width = w;}}var obj = new Rect(10, 5);console.log(obj.height, obj.width);*/class Rect {// 메소드area(h, w) {this.height = h;this.width = w;return this.height * this.width;}}var obj = new Rect();var a = obj.area(5, 7);console.log(a);console.log(obj.height, obj.width);</script></head><body><h3> 클래스 - 프로퍼티 </h3></body></html><!DOCTYPE html><html><head><meta charset="UTF-8"><title>Insert title here</title><link rel="icon" href="data:;base64,iVBORw0KGgo="><script type="text/javascript">class Car {constructor(name) {this.name = name;}speed() {console.log(`${this.name}은 시속 80 입니다.`);}color() {console.log(this.name +'은 검정색입니다.' );}}class Taxi extends Car {constructor(name) {super(name); // 상위 클래스의 생성자 호출}speed() {super.speed(); // 상위 클래스 메소드 호출console.log(this.name+'은 시속 100 입니다.');}}var obj = new Taxi('그랜저');console.log(obj.name);obj.speed();obj.color();</script></head><body><h3> 클래스 - 상속 </h3></body></html>자바스크립트도 자바처럼 상속의 개념이 있다.
자바의 super 개념도 동일하고 아버지 클래스의 요소들을 자식 클래스에서도 사용 가능
반응형'프로그래밍 > JavaScript 자바스크립트' 카테고리의 다른 글
자바스크립트 - JSON 데이터 객체로 변환하기 (0) 2021.09.30 자바스크립트 - apply / call / bind (0) 2021.09.30 자바스크립트 - 객체(3) (0) 2021.09.30 자바스크립트 - 배열 / 객체 (2) (0) 2021.09.30 자바스크립트 - 배열 / 객체 (1) (0) 2021.09.30