Read the Docs

[Read the Docs]: MDN Javascript Objects

onaeonae1 2022. 1. 19. 16:52

MDN Web Docs 에서 Javascript Object 에 대해서 설명한 것을 간단히 정리한 것

들어가는 글

  • MDN Web Docs 에서 Javascript Object 에 대해서 설명한 것을 몰랐던 부분 위주로 정리
  • 내가 몰랐던 부분 위주로 정리

요약

  • 객체를 생성하는 방법은 크게 2가지가 존재
  • class를 사용하지 않는 것, class를 사용하는 것

class를 사용하지 않는 것

객체 리터럴

  • 바로 object를 만들고 필드, 메소드를 선언해두는 것
  • dot, bracket을 사용해서 접근 가능
const person = {
	name:"onaeonae1",
	favoriteFood:"Orange",
	sayHello: function(){
		console.log(`${this.name} says Hello! He likes ${this.favoriteFood}`);
	}
}

person.sayHello(); //onaeonae1 says Hello! He Likes Orange

생성자 함수 사용

  • 생성자 함수를 만들고 new로 객체를 생성
  • 생성자 함수는 일반적으로 대문자로 시작하도록 선언
function Person(name, favoriteFood){
	this.name = name;
	this.favoriteFood = favoriteFood;
	this.sayHello = function(){
		console.log(`${this.name} says Hello! in constructor function. He Likes ${this.favoriteFood}`);
	};
}

const person2 = new Person("onaeonae1", "coffee");
person2.sayHello(); //onaeonae1 says Hello! in constructor function. He Likes coffee

new Object(), new Object(객체 리터럴), Object.create(기존 객체);

  • new Object, new Object(객체 리터럴)은 따로 설명할 것이 없음. 동일하게 작동
  • Object.create(기존 객체)는 기존 객체를 복사. 필드 메소드는 기존 객체와 똑같으므로 따로 변경
  • dot, brackets 등으로 접근해서 변경
let person3 = new Object();
let person4 = new Object({name:"onaeonae4", favoriteFood:"Pho Bo"});
let person5 = Object.create(person2);
person5.sayHello(); // onaeonae2 says Hello! in constructor function. He likes coffee
person5.name="onaeonae5";
person5.favoriteFood="Ramen";
person5.sayHello(); //onaeonae5 says Hello! in constructor function. He likes Ramen

프로토타입 기반 언어

모든 객체들이 Field, Method를 상속 받기 위한 템플릿으로서 프로토타입 객체를 가짐

지금 객체의 Prototype에서 상속 받고, 다시 그 위의 Prototype에서 상속 받고 ... 를 반복

이렇게 계속 접근하면서 상속 받는 것을 Prototype Chain 이라고 부름

let person1 = {//객체 리터럴}
person1.toString(); //[object Object]

// person1 에 toString 이라는게 없는데도 실제로는 작동함. Prototype Chain 을 거쳐 상속함

let person2 = new Person(); 
// 이때의 Prototype Chain 은 person2 -> Person -> Object 순으로

상속 in 생성자 함수

  • function 생성자는 상속을 처리하기에 약간 복잡하다.
  • call(this)라는 함수를 사용해 상위 생성자 함수에 접근해야 함.
  • 그래서 익히 알고 있는 class를 통한 OOP가 ES2015 부터 가능하다 야호

Class

constructor, super

  • constructor() 를 사용하는 것은 잘 알고 있으니 간단히 넘어가자 (다른 OOP와 마찬가지로 필드만 정의함)
  • super()에 대해서 정리해보자면, 한 class 에서 다른 class를 상속할 때(이 다른 class를 상위 class라고 하자) 상위 class의 생성자를 호출하는 것이다
  • 하위 class의 constructor() 에서 super()를 호출, 하위 class 에 특정적인 필드만 그 바깥에서 처리
class Person{
	constructor(name, favoriteFood){
		this.name = name;
		this.favoriteFood = favoriteFood;
	}
	sayHello(){
		console.log(`${this.name} says Hello in class. he likes ${this.favoriteFood}`);	
	}
};

class Teacher extends Person{
	constructor(name,favoriteFood, subject){
		super(name, favoriteFood);
		this.subject = subject;
	}
	introduceMySelf(){
		this.sayHello();
		console.log(`Teaches ${this.subject}`);
	}
};

const teacher1 = new Teacher("awesome_teacher", "Cider", "Literature");
teacher1.introduceMySelf(); 
// awesome_teacher says Hello in class. he likes Cider.
// Teaches Literature

getter, setter

  • 위와 같이 constructor 를 통해 모든 field를 처리하는 것은 이상적
  • 그러나 변경이 필요한 경우가 존재할 수 있음. (중간에 subject 나 favoriteFood 변경 등)
  • 이를 위해 필요한게 gettter , setter.
  • 이들은 get 변수명(){ return 변수명}, set 변수명(value){this.변수명 = value} 등으로 선언
  • 중요한건 이때 getter, setter와 통하는 멤버 변수는 앞에 ‘_’를 붙여야 함
  • 예시와 함께 보자
class Person{
	constructor(name, favoriteFood){
		this.name = name;
		this.favoriteFood = favoriteFood;
	}
	sayHello(){
		console.log(`${this.name} says Hello in class. he likes ${this.favoriteFood}`);	
	}
};

class Teacher extends Person{
	constructor(name,favoriteFood, subject){
		super(name, favoriteFood);
		this._subject = subject;
	}
	introduceMySelf(){
		this.sayHello();
		console.log(`Teaches ${this._subject}`);
	}
	get subject(){
		return this._subject;
	}
	set subject(newSubject){
		this._subject = newSubject;
	}
};

let teacher2 = new Teacher("bad_teacher", "Coke", "Math");
teacher2.introduceMySelf();
// bad teacher says Hello in class. he likes Coke.
// teaches Math

teacher2._subject = "Calculus";
teacher2.introduceMySelf();
// bad teacher says Hello in class. he likes Coke.
// teaches Calculus

getter, setter를 왜 쓰는거지?

  • 그러나 이미 알고 있을 만한 내용이겠지만, getter, setter를 통하지 않아도 get, set 이 가능하다
  • dot, brackets를 통해 바로 변경을 해줄 수 있다.
  • teacher2.favoriteFood=”steak”; 으로 변경하고 sayHello() 를 하면 변경된 내용 적용 확인 가능
  • 그래서 왜 쓰는 것일까? 라는 의문이 들었는데 아래의 링크를 보고 더 배울 수 있었다.

https://mygumi.tistory.com/161

 

getter setter in ES6 :: 마이구미

이번 글은 getter와 setter를 다뤄본다. getter와 setter에 대한 자료는 이해할 수 없는 글들과 궁금증을 해결시켜주는 못하는 글들이 대부분이다. 도대체 왜 getter와 setter 굳이 왜 쓰는지? 왜 써야하는

mygumi.tistory.com