웹프로그래밍 : Classes, Module, Standard Library

chanyeong yu ·2025년 4월 22일

웹프로그래밍

목록 보기
10/12

classes

옛날에 클래스를 만들던 방법

function range(from, to) {
  let r = Object.create(range.methods);
  r.from = from;
  r.to = to;
  return r;
}
-
range.methods = {
  includes(x) {
    return this.from <= x && x <= this.to;
  },
  // 이걸 만들어서 상속시켜줘야한다.
  *[Symbol.iterator]() {
    for (let x = Math.ceil(this.from); x <= this.to; x++) yield x;
  },
  toString() {
    return "(" + this.from + "..." + this.to + ")";
  },
};
  • [Symbol.iterator]를 상속시켜주어야한다.

prototype에 iterator넣기

Range.prototype = {
  constructor: Range,
  includes: function (x) {
    return this.from <= x && x <= this.to;
  },
  [Symbol.iterator]: function* () {
    for (let x = Math.ceil(this.from); x <= this.to; x++) yield x;
  },
  // Return a string representation of the range
  toString: function () {
    return "(" + this.from + "..." + this.to + ")";
  },
};
  • [Symbol.iterator]라는 function을 만들어주는 방법을 통해서 만들어줄 수 있다.

class 키워드

class Range {
  constructor(from, to) {
    this.from = from;
    this.to = to;
  }
  includes(x) {
    return this.from <= x && x <= this.to;
  }
  *[Symbol.iterator]() {
    for (let x = Math.ceil(this.from); x <= this.to; x++) yield x;
  }
  toString() {
    return `(${this.from}...${this.to})`;
  }
}
  • 이렇게 class 키워드를 사용하면 constructor로 초기화해줄 수 있고, 여기에 [Symbol.iterator]를 구현해주면 된다.
*[Symbol.iterator]() {
    for (let x = Math.ceil(this.from); x <= this.to; x++) yield x;
  },
  
  ----
  [Symbol.iterator]: function* () {
    for (let x = Math.ceil(this.from); x <= this.to; x++) yield x;
  },

Modules

  • 모듈 이전엔 html 파일에서 js파일을 일일히 로드해야했음.

  <body>
    <script type="text/javascript" src="./app.js"></script>
    <script type="text/javascript" src="./index.js"></script>
  </body>
</html>
  • 이렇게 불러오는건 아주아주 번거로운 일이다.
  • 또 전역 스코프에 함수가 노출되어 변경될 경우, 원하는 방향으로 사용하지 못하는 문제도 생길 수 있다.
module.exports = { mean, stddev};
const stats = require("./stats.js");

Webpack Module Bundler

  • 여러개의 파일을 하나의 파일로 합쳐주는 모듈 번들러
"build" : "webpack --config webpack.config.js

이 한줄을 package.json에 추가해준다.

그냥 Exports/Imports 쓰자...


Standard Library

Sets()

let s = new Set();
let t = new Set([1,s]);
let unique = new Set("Mississippi");
// "M", "i", "s", "p"
  • 순서가 없음.
  • 아무거나 들어갈 수 있음.
  • 중복이 없음.

0개의 댓글