Udemy - JavaScript: The Advanced Concepts
JS에서는 아래 두가지 패러다임을 모두 쓸수 있다!
function createElf(name, weapon) {
return {
name,
weapon,
atack : () => return 'atack with ' + weapon
}
}
const sam = createElf('Sam', 'bow');
const peter = createElf('Peter', 'bow');
객체를 하나하나 만들지 않을수 있게 되었다.
그래도 여전히 같은 함수가 반복 저장되어 메모리 낭비가 발생ㅜㅜ
const elfFunctions = {
attack: function() {
return 'atack with ' + this.weapon
}
}
function createElf(name, weapon) {
let newElf = Object.create(elfFunctions)
newElf.name = name;
newElf.weapon = weapon
return newElf
}
const sam = createElf('Sam', 'bow');
const peter = createElf('Peter', 'bow');
위의 문제를 해결했음. 좋긴 좋아.
그런데 이런 스타일을 그다지 볼수는 없어.(선호의 차이)
표준적인 OOP 코드 스타일이 아니어서...일까?
function Elf(name, weapon) {
this.name = name;
this.weapon = weapon;
}
Elf.prototype.attack = function() {
return 'atack with ' + this.weapon
}
const sam = new Elf('Sam', 'bow');
const peter = new Elf('Peter', 'bow');
Constructor 함수 방식을 사용 (Number, String과 같은...)
그런데 모두가 prototype에 대해 잘 알아? 해석하기 어렵지 않겠어?
class Elf {
//new 할때마다 실행되어 instance별로 다른 값을 가짐
constructor(name, weapon) {
this.name = name;
this.weapon = weapon;
}
//instance들이 함께 쓰는 함수 (이걸 constructor에 넣으면 메모리낭비)
attack() {
return 'atack with ' + this.weapon
}
}
const fiona = new Elf('Fiona', 'ninja stars');
console.log(typeof Elf) //function
console.log(typeof fiona) //object
OOP 스타일의 클래스를 적용!
하지만 사실은 클래스타입은 따로 없고 내부에서 prototype 이용해 만든것이다.
class Person {
constructor(nickName){
this.nickName = nickName;
}
familyName = 'hong';
#givenName = "GD"; //private field 나옴 (ES2020)
}
const son = new Person("pig");
console.log(son.familyName); // hong
console.log(son.nickName); //pig
console.log(son.#givenName); //Private field... error
class Character {
constructor(name, weapon) {
this.name = name;
this.weapon = weapon;
}
attack() {
return 'atack with ' + this.weapon
}
}
class Elf extends Character {
constructor(name, weapon, type) {
super(name, weapon)
this.type = type;
}
}
const houseElf = new Elf('Dolby', 'cloth', 'house')