23.7.12 TIL

김진주·2023년 7월 12일
0

TJL(Today Jinju Learned)

목록 보기
23/35

🏷️일반함수 단축구문

// 아래 두 객체는 동일하게 동작합니다.

user = {
  sayHi: function() {
    alert("Hello");
  }
};

// 단축 구문을 사용하니 더 깔끔해 보이네요.
user = {
  sayHi() { // "sayHi: function()"과 동일합니다.
    alert("Hello");
  }
};

SayBye는 단축구문으로 정의한 함수
SayHi는 단축구문이 아닌 평범하게 정의한 함수

⭐ 단축구문은 일반함수지만 prototype: {constructor}를 내장하지 않는다. 그러나 일반함수이기에 this도 단축구문을 사용하지 않은 일반함수처럼 잘 찾아줌!!
⭐ 객체의 메소드를 정의할 때 consise method만 사용하자!

🏷️객체의 메소드를 정의할 때 화살표 함수는 안되는 이유

const navigationMenu = {// 수정 전
  name: '글로벌 내비게이션',
  items: [
    { id: 'link-g', text: 'Google', link: 'https://google.com' },
    { id: 'link-n', text: 'Naver', link: 'https://naver.com' },
  ],
  getItem(index) {
    return this.items[index]; // this는 navigationMenu
  },
     addItem: (newItem) => {
     this.items.push(newItem); //this는 navi가 아닌 window이기 때문에 에러 발생 (widow.items.push())
   },

};

navigationMenu.getItem()
navigationMenu.addItem({
  id: 'link-l',
  text: 'Lycos',
  link: 'https://lycos.co.kr'
})

다음과 같이 작성하면 콘솔창에 에러가 뜨는데


push를 할 수 없다는 에러가 발생한다.
그 이유는 화살표함수를 사용하게 되면 this는 navi~가 아닌 window를 가리키기 때문에 에러 발생한다. 따라서 정확한 this를 찾기 위해서는 일반함수를 사용해야 한다.

const navigationMenu = { //수정 후
  name: '글로벌 내비게이션',
  items: [
    { id: 'link-g', text: 'Google', link: 'https://google.com' },
    { id: 'link-n', text: 'Naver', link: 'https://naver.com' },
  ],
  getItem(index) {
    return this.items[index]; // this는 navigationMenu
  },
  addItem(newItem) {
    this.items.push(newItem); //this는 navigationMenu
  },
};

navigationMenu.getItem()
navigationMenu.addItem({
  id: 'link-l',
  text: 'Lycos',
  link: 'https://lycos.co.kr'
})

📌프로토타입(객체지향)

🏷️프로토타입 상속

설명!object에서 프로퍼티를 읽으려고 하는데 해당 프로퍼티가 없으면 자바스크립트는 자동으로 프로토타입에서 프로퍼티를 찾기 때문이죠. 프로그래밍에선 이런 동작 방식을 '프로토타입 상속’이라 부릅니다.


찐객체가 만들어낸 자식 객체 animal은 __proto__를 사용해서 찐객체에 접근할 수 있다
Object.prototype === animal.__proto__는 같다.
Object.prototype - 찐객체에 바로 접근할 수 있고 객체를 생성하지 않고 사용 가능
객체.__proto__ - 양산품에서 찐객체에 접근할 일이 생길 때 사용

let animal = {
  eats: true
};
let rabbit = {
  jumps: true
};
//rabbit의 부모를 찐객체에서 animal로 바꿀 수 있음 (rabbit -> animal -> realObject)
rabbit.__proto__ = animal;

장점: rabbit.eats를 사용할 수 있음!! (상속 받았기 때문에)

this로 찾아지는 윈도우의 위치

찐객체 위의 null 찾기

🤔 프로토타입은 다른 자료형을 상속하면 그 자료형의 프로토타입 메서드도 사용할 수 있는건가요? ✅ yes

__proto__를 사용하지 않는 이유 -> 비표준이라

🏷️프로토타입 체이닝

let animal = {
  eats: true,
  walk() {
    alert("동물이 걷습니다.");
  }
};

let rabbit = {
  jumps: true,
  __proto__: animal
};

let longEar = {
  earLength: 10,
  __proto__: rabbit
};

// 메서드 walk는 프로토타입 체인을 통해 상속받았습니다.
longEar.walk(); // 동물이 걷습니다.
alert(longEar.jumps); // true (rabbit에서 상속받음)

⚠️ 프로토타입 체이닝의 제약사항

  1. 순환 참조(circular reference)는 허용되지 않습니다. __proto__를 이용해 닫힌 형태로 다른 객체를 참조하면 에러가 발생한다.
  2. __proto__의 값은 객체나 null만 가능합니다. 다른 자료형은 무시된다.
    ➕ 객체엔 오직 하나의 [[Prototype]]만 있을 수 있다.
    객체는 두 개의 객체를 상속받지 못한다.

🏷️enumerable(열거 가능한) 프로퍼티


enumerable 하지 못한 애들은 어두운 색으로 표시
for..in문에서 표시가 되지 않는 이유는 for..in문은 enumerable한 프로퍼티만 순회대상에 포함되기 때문이다.

🤔 우린 enumerable한 요소들만 만들 수 있는건가?
✅ Object.defineProperty()를 사용하면 enumerable 하지 않은 요소들도 만들 수 있다

🏷️함수의 프로토타입 프로퍼티

cat.hunt = function (target) {
  this.prey = target, 
  console.log(`${target}에게 슬금슬금 접근한다.`);
}

🤔 여기서의 this는 무엇일까?
✅ 정답 cat


return 값이 없기 때문에 undefined!!
화살표 함수는 함수로서의 기능만 하니까 constructor를 내장하고 있지 않기 때문에 new 키워드를 사용하여 객체를 만들 수 없다.
error 발생!!!

profile
진주링딩동🎵

0개의 댓글