20-21장 스터디 정리

김동현 (마늘향기)·2023년 5월 31일
0
  • 원시값을 접근할때는 래퍼 객체가 생성되고 접근한다. 객체를 원시값으로 변경하는 방법은 없을까?? (동현) 아래 mdn 예제 코드. (링크: [mdn 자료])
    // An object without Symbol.toPrimitive property.
    const obj1 = {};
    console.log(+obj1); // NaN
    console.log(`${obj1}`); // "[object Object]"
    console.log(obj1 + ""); // "[object Object]"
    
    // An object with Symbol.toPrimitive property.
    const obj2 = {
      [Symbol.toPrimitive](hint) {
        if (hint === "number") {
          return 10;
        }
        if (hint === "string") {
          return "hello";
        }
        return true;
      },
    };
    console.log(+obj2); // 10        — hint is "number"
    console.log(`${obj2}`); // "hello"   — hint is "string"
    console.log(obj2 + ""); // "true"    — hint is "default"
    아래 모던 자바스크립트 튜토 예제 코드. (링크: [모던 자바스크립트 튜토 자료])
    let user = {
      name: "John",
      money: 1000,
    
      // hint가 "string"인 경우
      toString() {
        return `{name: "${this.name}"}`;
      },
    
      // hint가 "number"나 "default"인 경우
      valueOf() {
        return this.money;
      }
    
    };
    
    alert(user); // toString -> {name: "John"}
    alert(+user); // valueOf -> 1000
    alert(user + 500); // valueOf -> 1500
profile
안녕하세요, 김동현입니다. 공부한 내용을 기록하고자 블로그를 생성하였습니다. 감사합니다.

0개의 댓글