클래스
자바스크립트는 클래스기반은 아니고 프로토타입 언어이다.
// prototype
// const fruits = ['Apple', 'Banana', 'Cheery'];
const fruits = new Array('Apple', 'Banana', 'Cheery');
console.log(fruits); // ['Apple', 'Banana', 'Cheery']
console.log(fruits.length); // 3
console.log(fruits.includes('Banana')); // true
console.log(fruits.includes('Orange')); // false
// .length나 .includes 같은 것을 프로토타입 속성, 프로토타입 메소드라고 한다.
// 프로토타입은 new 키워드를 통해서 만드는 생성자 함수에서 반환된 결과. fruits라는 하나의 배열 데이터, istance 에서 쓸 수 있는 메소트나 객체
// 자바스크립트에서 배열 데이터는 생성자함수에서 반환 된 instance이다.
// 사용 편의를 위해 레터럴 방식을 썼던 거임
Array.prototype.heropy = function () {
console.log(this);
}
fruits.heropy();
const arr = [];
arr.heropy();
// const heropy = {
// firstName: 'Heropy',
// lastName: 'Park',
// getFullName() {
// return `${this.firstName} ${this.lastName}`;
// }
// }
// const neo = {
// firstName: 'Neo',
// lastName: 'Anderson',
// // getFullName() {
// // return `${this.firstName} ${this.lastName}`;
// // }
// }
// console.log(heropy.getFullName());
// // console.log(neo.getFullName());
// console.log(heropy.getFullName.call(neo));
function User(first, last) {
this.firstName = first;
this.lastName = last;
}
User.prototype.getFullName = function () {
return `${this.firstName} ${this.lastName}`;
}
const heropy = new User('Heropy', 'Park');
const neo = new User('Neo', 'Anderson');
console.log(heropy);
console.log(neo);
console.log(heropy.getFullName());
console.log(neo.getFullName());
// ES6 Classes
// function User(first, last) {
// this.firstName = first;
// this.lastName = last;
// };
// User.prototype.getFullName = function () {
// return `${this.firstName} ${this.lastName}`;
// };
class User {
constructor(first, last) {
this.firstName = first;
this.lastName = last;
};
getFullName() {
return `${this.firstName} ${this.lastName}`;
}
};
const heropy = new User('Heropy', 'Park');
const neo = new User('Neo', 'Anderson');
// User 함수, User 객체 등으로 불림
console.log(heropy);
console.log(neo);
console.log(heropy.getFullName());
console.log(neo.getFullName());
// Getter, Setter
class User {
constructor(first, last) {
this.firstName = first;
this.lastName = last;
// this.fullName = `${first} ${last}`; 생성자 함수를 통해서 만들었을 때, 초기화, 그 이후 firstName을 바꿔도 반영되지 않음
};
getFullName() {
return `${this.firstName} ${this.lastName}`;
// 함수를 통해서 만들면, 생성자 함수의 값을 바꾸면, fullname이 정상적으로 출력 됨
}
};
const heropy = new User('Heropy', 'Park');
console.log(heropy.getFullName());
heropy.firstName = 'Neo';
console.log(heropy.getFullName());
class User {
constructor(first, last) {
this.firstName = first;
this.lastName = last;
};
get fullName() {
console.log('Getting full name!');
return `${this.firstName} ${this.lastName}`;
// get이라고 앞에 붙이고, 쓰면 이게 Getter
// 호출할 때는 ()붙이지 않고 속성처럼 사용한다.
};
set fullName(value) {
console.log(value);
[this.firstName, this.lastName] = value.split(' ');
};
};
const heropy = new User('Heropy', 'Park');
console.log(heropy.fullName);
heropy.firstName = 'Neo';
console.log(heropy.fullName);
heropy.fullName = 'Neo Anderson';
console.log(heropy);
// 정적 메소트(Static methods)
class User {
constructor(first, last) {
this.firstName = first;
this.lastName = last;
};
getFullName() {
return `${this.firstName} ${this.lastName}`;
}
static isUser(user) {
if (user.firstName && user.lastName) {
return true;
}
return false;
}
};
// 일반 메소트 혹은 프로토타입 메소드는 기본적으로 istance에서 사용하는 메소드이고,
//static이라는 키워드가 붙어 있는 정적 메소드는 인스턴스에서 사용할 수 없고, 클래스 자체에서 사용해야 한다.
// static이 붙은 정적 메소드는 User라는 class의 일종의 보조 함수로서 사용한다.
const heropy = new User('Heropy', 'Park');
const neo = new User('Neo', 'Anderson');
const lewis = {
name: 'Lewis Yang',
age: 85,
}
console.log(heropy.getFullName());
console.log(neo.getFullName());
console.log(User.isUser(heropy));
console.log(User.isUser(neo));
console.log(User.isUser(lewis));
// 상속(Inheritance)
// 운송수단
class Vehicle {
constructor(acceleration = 1) {
this.speed = 0;
this.acceleration = acceleration;
};
accelerate() {
this.speed += this.acceleration;
};
decelerate() {
if (this.speed <= 0) {
console.log('정지!');
return;
}
this.speed -= this.acceleration;
};
};
// 자전거
class Bicycle extends Vehicle {
constructor(price = 100, acceleration) {
super(acceleration);
this.price = price;
this.wheel = 2;
};
};
const bicycle = new Bicycle(300);
bicycle.accelerate();
bicycle.accelerate();
console.log(bicycle);
console.log(bicycle instanceof Bicycle);
console.log(bicycle instanceof Vehicle);
// 자동차
class Car extends Bicycle {
constructor(license, price, acceleration) {
super(price, acceleration);
this.license = license;
this.wheel = 4;
};
// 오버라이딩(Overriding) : 상속받은 메소드를 같은 이름으로 다시 만든거
accelerate() {
if (!this.license) {
console.error('무면허!');
return;
}
this.speed += this.acceleration;
console.log('가속!', this.speed);
}
};
const carA = new Car(true, 7000, 10);
const carB = new Car(false, 4000, 6);
carA.accelerate();
carA.accelerate();
carB.accelerate();
console.log(carA instanceof Vehicle);
console.log(carB instanceof Vehicle);
// 보트
class Boat extends Vehicle {
constructor(price, acceleration) {
super(acceleration);
this.price = price;
this.moter = 1;
};
};
const boat = new Boat(10000, 5);
console.log(boat instanceof Car);
// instanceof : 인스턴스가 만들어진 해당하는 클래스나, 그 해당하는 클래스가 상속받고 있는 클래스, 그 상속의 상속에 포함 여부, true, false 반환
class A {
constructor() {
};
};
class B extends A {
constructor() {
super();
};
};
class C extends B{
constructor() {
super();
};
};
const a = new A();
const b = new B();
const c = new C();
console.log(c instanceof A);
console.log(c instanceof B);
console.log(c instanceof C);
// instanceof 키워드를 쓰면 상속받은 class도 모두 true가 나온다
console.log(c.constructor === A);
console.log(c.constructor === B);
console.log(c.constructor === C);
// .constructor라는 속성을 비교하면 해당하는 인스턴스가 어떤 class에서 만들어진지 앟 수 있다.
const fruits = ['Apple', 'Banana'];
// const fruits = new Array('Apple', 'Banana');
// 위 두가지가 완전하게 같다는 것을 증명한다, constructor가 같다는 것이
console.log(fruits.constructor === Array);
console.log(fruits instanceof Array);
'Javascript' 카테고리의 다른 글
javascript 표준내장객체 (1) | 2024.01.15 |
---|---|
javascript 문법 - 함수 (1) | 2024.01.15 |