tech.junha.kr

노트/JavaScript

Object

작성 수정

1. dynamic typing

  • 다른 언어에서는 흔치 않은 일이지만, 오브젝트의 프로퍼티를 중간에 추가할 수 있다.
const obj = {
    name: 'junha',
    age: '20',
};

junha.age = 21; // ✅
junha.hasDog = true; // ✅
  • const 키워드로 저장되어 obj가 가리키는 포인터는 잠겨있어, 다른 값으로 할당할 수 없다.
  • 하지만 오브젝트의 각각의 프로퍼티는 포인터가 가리키고 있는 메모리에 다른 값을 할당할 수 있다.

2. Computed properties

  • Object['key']표기법
  • 동적으로 key에 관한 value를 받아올 때 사용한다.
function printValue(obj, key) {
    console.log(obj.key);   // ❌ obj.key undefined
}

function printValueComputed(obj, key) {
    console.log(obj[key]);  // ✅ obj.name junha
}

printValue(obj, 'name');
printValueComputed(obj, 'name');

3. function is object

  • 함수는 object다.
    1. 함수를 변수에 할당하거나
    2. 함수 자체를 값으로써 리턴할 수 있다.
const func = function () {
  ...
}
function func2() {
  ...
  return function () {
    ...
  }
}
  • 모든 함수는 return undefined가 생략되어있다.

4. Constructor Function

  • 다른 계산을 하지 않고 순수하게 Object를 생성하는 함수
  • 대문자로 이름을 만든다.
function Person(name, age) {
    //this = {}
    this.name = name;
    this.age = age;
    //return this
}
const yunjung = new Person('yunjung',21))
console.log(yunjung)  // Person {name: 'yunjung', age: 21}

6. for in, for of

for (key in ellie) {
    console.log(key);
}

for (value of iterable) {
    console.log(value);
}

7. 복제

// ❌
const user1 = { name: 'junha', age: 20 };
const user2 = user1;
user2.name = 'hajun';
  • user1, user2의 레퍼런스가 동일하기 때문에 user1의 name도 hajun으로 변한다.

옛날 방식

const user3 = {};
for (key in user) {
    user3[key] = user[key];
}

Object.assign(target, source)

  • 리턴값: target 객체인데, 이제 그 source를 병합한
const user1 = {name:'junha'};
const user2 = {age: 30}

const user3 = Object.assign(user1, user2);
// user1 === user3

const user4 = Object.assign({}, user1, user2);
// 새로운 객체 user4 생성
const fruit1 = { color: 'red', price: 'high' };
const fruit2 = { color: 'blue', size: 'big' };

const mixed = Object.assign({}, fruit1, fruit2);
// mixed: {color: 'blue', price: 'high', size: 'big'}
// color 프로퍼티는 오버라이딩 된다.

8. examples

객체안에서의 메소드 (this 활용)
const TwoDotDistance = {
  point1: {
    x: 0,
    y: 0,
  },

  point2: {
    x: 0,
    y: 0,
  },

  setPoints: function (x1, y1, x2, y2) {
    this.point1.x = x1;
    this.point1.y = y1;
    this.point2.x = x2;
    this.point2.y = y2;
  },

  calculateDistance: function () {
    const d = Math.sqrt(
      Math.pow(this.point1.x - this.point2.x, 2) +
        Math.pow(this.point1.y - this.point2.y, 2)
    );
    if (isNaN(d)) {
      return 0;
    } else {
      return d.toFixed(2);
    }
  },
};

export default TwoDotDistance;