LoginSignup
0
0

More than 5 years have passed since last update.

Object to primitive conversion

Posted at
file.js
obj[Symbol.toPrimitive] = function(hint) {
  // return a primitive value
  // hint = one of "string", "number", "default"
}

let user = {
    name: "John",
    money: 1000,

    [Symbol.toPrimitive](hint) { //원시로~
        alert(`hint:${hint}`);    //$ 는 역따옴표안에서 사용가능
        return hint == "string" ? `{name: "${this.name}"}`:this.money;
    }

};
alert(user); // hint: string -> {name: "John"}
alert(+user); // hint: number -> 1000
alert(user + 500); // hint: default -> 1500

자바스크립트는 기본타입과 참조타입(객체)으로 나눌 수 있습니다.
기본타입을 원시 데이터라고 하며 5, 'foo', true, false, null, undefined 와 같은 자바스크립트 값을 말합니다.

즉, 숫자, 문자열, 불리언, null, undefined 인 다섯가지 기본 타입을 말하며 이 자바스크립트값은 더 이상 단순화할 수 없기 때문에 원시적(primitive)이라 하며, 이러한 값을 가리켜 원시값이라 합니다.

출처: http://webclub.tistory.com/240 [Web Club]

ToPrimitive and ToString/ToNumber

file.js
let obj = {
    toString() {
        return "2"
    }
}
alert(obj * 2); //4
//수학연산(바이너리 플러스 제외)는 ToNumber 변환을 수행한다

let obj = {
    toString() {
        return "2"
    }
}
alert(obj + 2) //22

let obj = {
    toString() {
        return true;
    }
}

alert(obj +2); //3
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0