데이터 타입, 실행 컨텍스트

베니·2022년 5월 2일
0

JS

목록 보기
22/24
post-thumbnail

데이터 타입

  • 깊은 복사(내부 프로퍼티를 순회하며 함수를 재귀적으로 호출하는 방식)
const copyObjectDeep = function(target) {
  const result = {};
  if (typeof target === 'object' && target !== null) {
    for (let prop in target) {
      result[prop] = copyObjectDeep(target[prop]);
    }
  } else {
    result = target;
  }
  return result;
};
  • 깊은 복사(JSON을 활용한 방식)
const copyObjectViaJSON = function (target) {
  return JSON.parse(JSON.stringify(target));
};
const obj = {
  a: 1,
  b: {
    c: null,
    d: [1, 2],
    func1: function () { console.log(3); }
  },
  func2: function () { console.log(4); }
};

const obj2 = copyObjectViaJSON(obj);

obj2.a = 3;
obj2.b.c = 4;
obj.b.d[1] = 3;

console.log(obj); // { a: 1, b: { c: null, d: [1, 3], func1: f() }, func2: f() }
console.log(obj2); // { a: 3, b: { c: 4, d: [1, 2] } }

JSON 문법으로 표현된 문자열로 전환했다가 다시 JSON 객체로 바꾸는 방법이다. JSON이 처리 가능한 7가지 타입(string, number, object, array, true, false, null)으로 한정되어 있기때문에 function 타입은 복사할 수 없다.

함수를 복사하고 싶다면 재귀함수를 이용한 방식, lodash, ramda 라이브러리를 사용하자!

실행 컨텍스트

실행 컨텍스트의 구성

  • Variable Environment
  • Lexical Environment
    • Environment Record(호이스팅)
    • outerEnvironmentReference(스코프체인)
  • thisBinding

Variable Environment에 담기는 내용은 LexicalEnvironment와 같지만 최초 실행 시의 스냅샷을 유지한다는 점이 다르다. 실행 컨텍스트를 생성할때 VariableEnvironment에 정보를 먼저 담은 다음, 이를 그대로 복사해서 LexicalEnvironment를 만들고, 이후에는 LexicalEnvironment를 주로 활용하게 된다.

참고

코어 자바스크립트

profile
안녕하세요~

0개의 댓글