[TIL. 04] JavaScript - object 2

신지원·2021년 2월 18일
0

JavaScript

목록 보기
3/5
post-thumbnail

1. 객체에서의 this 키워드

const goat = {
  dietType: 'herbivore',
  makeSound() {
    console.log('baaa');
  },
  diet() {
    console.log(this.dietType);
  }
};
 
goat.diet(); 
// Output: herbivore
  • 함수를 객체인goat의 method로서 사용했다. 이런 경우, this는 해당 object의 property에 접근 할 수 있게 해준다.

  • arrow function 에서 this 는 상위 scoope를 가리킨다. (Lexical this)

2. 객체에서의 method (es6)

const goat = {
  name: 'Billy',
  color: 'biege',
  giveDetails(){
    console.log(`${this.name} is a ${this.color} goat.`)
  },   // method 작성법 1 (shorthand format)
  giveDetails: function() {
    console.log(`${this.name} is a ${this.color} goat.`)
  } // method 작성법 2 (longhand format)

}

3. Get, Set

3-1. getter

const person = {
  _firstName: 'John',
  _lastName: 'Doe',
  get fullName() {
    if (this._firstName && this._lastName){
      return `${this._firstName} ${this._lastName}`;
    } else {
      return 'Missing a first name or a last name.';
    }
  }
}
 
// To call the getter method: 
person.fullName; // 'John Doe'
  • 인수가 없고, 객체 내부 property를 읽을 때 사용함.

  • 함수처럼 호출하지 않고, 객체의 일반 property들에 접근하는 것 처럼 평범하게 objName.getmethodName(person.fullName)처럼 사용함.

  • getter는 조건문을 사용해서 다른 값을 리턴 할 수 있다.

_(underscore) 사용 이유는 내부에서만 사용할 변수나 함수일때 붙인다.(private) (그냥 관습같은 것임)

3-2. setter

const person = {
  _age: 37,
  set age(newAge){
    if (typeof newAge === 'number'){
      this._age = newAge;
    } else {
      console.log('You must assign a number to age');
    }
  }
};


person.age = 40;
console.log(person._age); // Logs: 40
person.age = '40'; // Logs: You must assign a number to age
  • 인수가 하나 있고, property 에 값을 쓸때 사용한다.

  • getter 처럼 method 호출할때 괄호 필요 없다.

4. Factory Functions

const monsterFactory = (name, age, energySource, catchPhrase) => {
  return { 
    name: name,
    age: age, 
    energySource: energySource,
    scare() {
      console.log(catchPhrase);
    } 
  }
};

const ghost = monsterFactory('Ghouly', 251, 'ectoplasm', 'BOO!');
ghost.scare(); // 'BOO!'
  • 팩토리 함수는 객체를 반환한다.

  • 파라미터로 객체를 변경하여 반환할 수 있다.

5. Property Value Shorthand (단축 속성명)

const monsterFactory = (name, age) => {
  return { 
    name: name,
    age: age
  }
}; //factory function


const monsterFactory = (name, age) => {
  return { 
    name,
    age 
  }
}; // property shorthand
  • 객체를 정의 할 때 객체의 key값과 value의 값이 같으면, key 와 value 값을 각각 표기하지 않고 한 번만 표기하는 것이다.

6. Destructured Assignment(구조 분해 할당)

const vampire = {
  name: 'Dracula',
  residence: 'Transylvania',
  preferences: {
    day: 'stay inside',
    night: 'satisfy appetite'
  }
};

// residence를 변수로 추출할때
const residence = vampire.residence; 
console.log(residence); // Prints 'Transylvania' 

// destructed assignment 를 이용하면 이런 식.
const { residence } = vampire; 
console.log(residence); // Prints 'Transylvania'

//day를 변수로 추출할 때
const { day } = vampire.preferences; 
console.log(day); // Prints 'stay inside'
  • 객체의 key-value를 변수로 추출할 수 있다.

  • {} 를 이용해서 property를 변수로 추출한다.

0개의 댓글