부트캠프/자바스크립트 완벽 가이드

[JavaScript] Symbol.toStringTag

하이고니 2023. 3. 6. 14:55

 

 

기본 자바스크립트 객체에서 toString() 메서드를 호출하면 [object Object]가 반환된다.

 

{}.toString()	// => "[object Object]"

 

같은 Object.prototype.toString() 함수를 내장 타입의 인스턴스 메서드처럼 호출하면 다른 방법으로는 얻을 수 없는 객체의 타입 정보를 얻을 수 있다.

 

Object.prototype.toString.call([])		// => "[object Array]" 
Object.prototype.toString•call(/./)		// => "[object RegExp]" 
Object.prototype.toString.call(()=>{})		// => “[object Function]"
Object.prototype.toString.call("")		// => "[object String]"
Object.prototype.toString.call(0)		// => "[object Number]"
Object.prototype.toString•call(false)		// => "[object Boolean]"

 

다음  classof() 함수는 객체 타입을 구분하지 않는 typeof 연산자보다 좀 더 유용하다.

 

function classof(o) {
  return Object.prototype.toString.call(o).slice(8, -1);
}

classof(null)         // => "Null"
classof(undefined)    // => "Undefined"
classof(1)            // => "Number"
classof(10n ** 100n)  // => "Biglnt"
classof("")           // => "String"
classof(false)        // => "Boolean"
classof (Symbol())    // => "Symbol"
classof({})           // => "Object"
classof([])           // => "Array"
classof(/./)          // => "RegExp"
classof(()=>{})       // => "Function"
classof (new Map())   // => “Map”
classof(new Set())    // => "SetN 
classof(new Date())   // => "Date"

class Range {
  get [Symbol.toStringTag]() { return "Range" }
  // 나머지 클래스 정의는 생략한다.
}

let r = new Range(1, 10);
classof(r)  // => "Range"