Javascript에서 코딩 중. 궁금해져서 찾아본 차이.
요약하자면,
- String()과 toString()은 동작하는 방식이 다르다.
- String(value)로 부르는 경우 value object의 마지막에 toString() 함수를 호출하여 값을 가져옴.
- toString(value)의 경우, null이나 undefined일 경우, TypeError Exception이 발생함. (위의 경우는 "null")
- String(value) 방식은 toString()함수를 호출할때, primitive 값이 없으면, valueOf()함수를 리턴하고, 해당 함수의 리턴 값마저 primitive 값이 없으면, TypeError Exception이 발생함.
<Stack Overflow 에서 찾은 답변. 링크>
They are not completely the same, and actually, the String constructor called as a function (your first example), will at the end, call the toString method of the object passed, for example:
var o = { toString: function () { return "foo"; } };
String(o); // "foo"
On the other hand, if an identifier refers to null or undefined, you can't use the toString method, it will give you a TypeError exception:
var value = null;
String(null); // "null"
value.toString(); // TypeError
The String constructor called as a function would be roughly equivalent to:
value + '';
The type conversion rules from Object-to-Primitive are detailed described on the specification, the [[DefaultValue]] internal operation.
Briefly summarized, when converting from Object-to-String, the following steps are taken:
- If available, execute the toString method.
- If the result is a primitive, return result, else go to Step 2.
- If available, execute the valueOf method.
- If the result is a primitive, return result, else go to Step 3.
- Throw TypeError.
Given the above rules, we can make an example of the semantics involved:
var o = {
toString: function () { return "foo"; },
valueOf: function () { return "bar"; }
};
String(o); // "foo"
// Make the toString method unavailable:
o.toString = null;
String(o); // "bar"
// Also make the valueOf method unavailable:
o.valueOf = null;
try {
String(o);
} catch (e) {
alert(e); // TypeError
}
'IT > 개발자' 카테고리의 다른 글
706.Design HashMap (Leet Code) (0) | 2023.10.04 |
---|---|
416. Partition Equal Subset Sum (Leet Code) (1) | 2023.10.03 |
티스토리 파일첨부 OPEN API 오류 400 Error (25) | 2020.06.12 |
쇼핑몰 실시간재고 알림 봇 만들기 (2.텔레그램 Bot) (0) | 2020.05.04 |
쇼핑몰 실시간재고 알림 봇 만들기 (1.파이썬 웹 크롤링 + BeautifulSoup) (2) | 2020.03.29 |