개발/Javascript

Object Model

치돈포에버 2022. 6. 6. 20:09

*복습 자료라서 뻔한 내용은 생략

 

 

Summary.

 

 

1. Object는 기본적으로 Reference

// Two variables, a single object
const fruit = {name: 'apple'};
const fruitbear = fruit;  // Assign fruit object reference to fruitbear

// Here fruit and fruitbear are pointing to same object
fruit == fruitbear; // return true
fruit === fruitbear; // return true

fruit.name = 'grape';
console.log(fruitbear); // output: { name: "grape" }, instead of { name: "apple" }

 

2. getter, setter 설정 가능 (object initializer에서 하거나 Object.defineProperties()로 나중에 추가하거나)

const o = {
  a: 7,
  get b() {
    return this.a + 1;
  },
  set c(x) {
    this.a = x / 2;
  }
};

console.log(o.a); // 7
console.log(o.b); // 8 <-- At this point the get b() method is initiated.
o.c = 50;         //   <-- At this point the set c(x) method is initiated
console.log(o.a); // 25
const o = { a: 0 };

Object.defineProperties(o, {
     'b': { get: function() { return this.a + 1; } },
     'c': { set: function(x) { this.a = x / 2; } }
});

o.c = 10; // Runs the setter, which assigns 10 / 2 (5) to the 'a' property
console.log(o.b); // Runs the getter, which yields a + 1 or 6

 

3. this는 현재 Object를 가리킴. this.prop을 사용하는 함수를 Object에 추가하면 해당 Object의 prop을 참조

 

4. method는 function type인 property. 아래처럼 다양한 정의방법이 있음

objectName.methodName = functionName;

const myObj = {
  myMethod: function(params) {
    // ...do something
  },

  // this works too!
  myOtherMethod(params) {
    // ...do something else
  }
};

 

5. Property 순회하는 방법은 3가지

    + for in

    + Object.keys(o)

    + Object.getOwnPropertyNames(o)

    + 모든 Prototype Chain에 있는 Property 순회하려면 다음과 같은 방법 뿐 (Native 방법은 없음)

function listAllProperties(o) {
  let objectToInspect = o;
  let result = [];

  while(objectToInspect !== null) {
    result = result.concat(Object.getOwnPropertyNames(objectToInspect));
    objectToInspect = Object.getPrototypeOf(objectToInspect)
  }

  return result;
}

 

6. Object 생성하는 법 3가지

    + Object Initializer (Literal)

    + Constructor 함수 정의하고 new 붙여서 생성 (이름은 Capital로 하는 것이 Convention)

    + Object.create() 함수 사용 (Constructor 함수 안만들어도 돼서 편리)

function Car(make, model, year) {
  this.make = make;
  this.model = model;
  this.year = year;
}

const myCar = new Car('Eagle', 'Talon TSi', 1993);
// Animal properties and method encapsulation
const Animal = {
  type: 'Invertebrates', // Default value of properties
  displayType: function() {  // Method which will display type of Animal
    console.log(this.type);
  }
};

// Create new animal type called animal1
const animal1 = Object.create(Animal);
animal1.displayType(); // Output: Invertebrates

 

 

Additional.

1. Property는 기본적으로 String으로 변환될 수 있는 어떤 type도 가능하지만 valid identifier가 아닌 경우 dot notation이 아닌 [ ]로만 접근 가능 

 

2. (다음에) Class-based와 Prototype-based 차이 공부하기 (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Details_of_the_Object_Model)

 

 

Reference.