개발일지

[JS] 11. JavaScript 정리 본문

JS, TS/[TS | 강의] TS·OOP

[JS] 11. JavaScript 정리

lyjin 2022. 11. 10.

Proto:

  • JS는 프로토타입 기반의 언어로 모든 객체들이 상속 받기 위한 템플릿으로 prototype object 를 가진다.
  • 상속되는 속성, 메소드들은 객체가 아닌 prototype 속성에 정의 ( __proto__ )
  • 즉, JS에서 상속, 코드 재사용 등 OOP을 위해 사용하는 것!

 

Proto 속성

  • JS에서 모든 객체는 Object type을 상속한다.
  • Object.prototype 으로 접근 가능
/** Proto */
const x = {};
const y = {};
console.log(x);  // __proto__: Object
console.log(y);  // __proto__: Object
console.log(x.toString());
console.log(x.__proto__ === y.__proto__); // true

/** Array */
const array = [];
console.log(array);  // __proto__: Array
// __proto__ 안에 __proto__: Object 존재 >> Object 상속

 


instance member level VS prototype member level

function CoffeeMachine(beans) {
  this.beans = beans;

  // 1. Instance member level : 생성되는 인스턴스들 모두 공통으로 갖게 됨
  this.makeCoffee = shots => {
    console.log('making... ☕️');
  };
}

// 2. Prototype member level : __proto__ 속성으로 들어가게 됨
CoffeeMachine.prototype.makeCoffee = (shots) => {
  console.log('making... ☕️');
};

const machine1 = new CoffeeMachine(10);
const machine2 = new CoffeeMachine(20);
console.log(machine1);
console.log(machine2);

상속 받기

function LatteMachine(milk) {
  this.milk = milk;
}

LatteMachine.prototype = Object.create(CoffeeMachine.prototype); // 상속

const latteMachine = new LatteMachine(123);
console.log(latteMachine);
latteMachine.makeCoffee();  // 사용가능
  • [Object.create(proto)](https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Object/create): 지정된 proto의 객체 및 속성을 갖는 새 객체 생성

 

참고)

https://developer.mozilla.org/ko/docs/Learn/JavaScript/Objects/Object_prototypes

 


This:

  • 다른 언어에서 this 는 생성된 인스턴스를 가리키지만, JS에서 this 는 호출한 방법에 의해 결정된다.

 

Global context

  • Global context에서의 this 는 전역 객체를 참조한다.
  • 웹 브라우저에서는 window 가 전역 객체
console.log(this); // window

function simpleFunc() {
  console.log(this);
}
simpleFunc();        // window
window.simpleFunc(); // window

Global Object로 등록하기

  • 함수는 글로벌 객체에 등록 가능 > 글로벌 객체(window)로 접근 가능
    • ex) window.func
  • let, const로 선언된 변수는 접근 불가능
  • 예외) var은 접근 가능!
class Counter {
  count = 0;
  increase = function () {
    console.log(this);
  };
}

// 예제1. 변수
const counter = new Counter();
counter.increase(); // Counter

const caller = counter.increase;
caller(); // undefined

// 예제2. 함수
class Bob {}
const bob = new Bob();
bob.run = counter.increase;
bob.run(); // Bob

 


Conter와 연결하고 싶으면?

// 1. bind()
const caller = counter.increase.bind(counter);

// 2. 화살표 함수: 선언될 때의 this scope 유지햐게 됨
class Counter {
  count = 0;
  increase = () => {
    console.log(this);
  };
}

class Bob {}
const bob = new Bob();
bob.run = counter.increase;
bob.run(); // Counter

 

 


Module:

  • export: 모듈 내보내기
  • import: 모듈 가져오기

모듈화 하지 않으면 모두 global scope 설정되기 때문에 import 없이 사용 가능하다.

 

// module1.js

function addGlobal(a, b) {
  return a + b;
}

 

// module2.js

console.log(addGlobal(1, 2)); // 3
// window.add(1, 2) 사용 가능

 


export

// module1.js

export const number = 10;

export function add(a, b) {
  return a + b;
}

export function print() {
  console.log('print');
}

 

// module2.js
import * as calculator from './10-3-module1.js';

calculator.number;
calculator.add(1, 2);
calculator.print();

 


export default

  • 기본값으로 내보낼 함수, 객체를 정해줄 수 있다.
  • import 할 때 원하는대로 이름을 변경할 수 있다.
  • default는 모듈 당 하나만 정의 가능
// module1.js

export default function add(a, b) {
  return a + b;
}

export function mul(a, b) {
  return a * b;
}

 

// module2.js 예시1.
import run from './10-3-module1.js';

run(1, 2);

 

// module2.js 예시2.
import run, { mul } from './10-3-module1.js';

run(1, 2);  // add(1,2)
mul(1, 2);