var s = new String("Hello World!");
var a = new String("abc");
typeof a; // "object"..."String"이 아니다!
a instanceof String; // true
Object.prototype.toString.call(a); // "[object String]"
new String("abc")
생성자의 결과는 원시 값 “abc”를 감싼 객체 래퍼이다. (원시 값 “abc”는 아니다.)typeof
연산자로 이 객체의 타입을 보면 자신을 감싼 원시 값의 타입이 아닌 object의 하위 타입에 가깝다.Object.prototype.toString()
이라는 메서드에 값을 넣어 호출함으로써 존재를 엿볼 수 있다.
Object.prototype.toString.all([1, 2, 3]);
// "[object Array]:
Object.prototype.toString.call( /regex-literal/i );
// "[object RegExp]"
내부 [[Class]] 값이 배열은 “Array”, 정규식은 “RegExp”임을 알 수 있다.
Object.prototype.toString.call(null);
// "[object Null]"
Object.prototype.toString.call(undefined);
// "[object Undefined]"
Null(), Undefined() 같은 네이티브 생성자는 없지만 내부 [[Class]] 값은 있는것처럼 나온다.
Object.prototype.toString.call("abc");
// "[object String]"
Object.prototype.toString.call(42);
// "[object Number]"
Object.prototype.toString.call(true);
// "[object Boolean]"
내부 [[Class]] 값이 각각 String, Number, Boolean으로 표시된 것으로 보아 단순 원시 값은 해당 객체 래퍼로 자동 박싱됨을 알 수 있다.
.length
, .toString()
으로 접근하려면 원시 값을 객체 래퍼로 감싸줘야 한다.a="abc"; a.length;
와 같은 코드가 가능하다.new String("abc")
가 아닌 "abc"
를 사용해야한다.Object()
함수를 이용하자. (new 키워드는 없다.)valueOf()
메서드로 추출한다.
var a = new String("abc");
var b = new Number(42);
var c = new Boolean(true);
a.valueOf(); // "abc"
b.valueOf(); // 42
c.valueOf(); // true
다시 말하지만 이 방법은 전혀 추천하지 않는다. 알고만 있자.
var a = new Array(1, 2, 3); // new 생략 가능
a; // [1, 2, 3]
var b = [1, 2, 3];
b; // [1, 2, 3]
new Date()
로 생성한다. 이 생성자는 날짜/시각을 인자로 받는다. 인자를 생략하면 현재 날짜/시각으로 대신한다.getTime()
을 호출하면 된다.Date.now()
를 사용하자.obj[Symbol.iterator] = function() { /*...*/ }
var mysym = Symbol("my own symbol")
mysym; // Symbol(my own symbol)
mysym.toString(); // "Symbol(my own symbol)"
typeof mysym; // "symbol"
var a = {};
a[mysym] = "foobar";
Object.getOwnPropertySymbols(a);
// [Symbol(my own symbol)]
.prototype
객체를 가진다.Array.prototype
, String.prototype
, …String.prototype
객체에 정의된 메서드에 접근할 수 있다.
String.prototype.XYZ
와 같은 것을 String#XYZ
처럼 줄여 쓰는 것이 관례String#indexOf()
: 문자열에서 특정 문자의 위치를 검색String#charAt()
: 문자열에서 특정 위치의 문자를 반환String#substr()
: 문자열의 일부를 새로운 문자열로 추출String#toUpperCase()
: 대문자로 변환된 새로운 문자열을 생성String#trim()
: 앞/뒤 공란이 제거된 새로운 문자열 생성
프로토타입 위임 덕분에 모든 문자열이 이 메서드들을 사용할 수 있다.
이 중 문자열 값을 변경하는 메서드는 없다. 수정이 일어나면 늘 기존 값으로부터 새로운 값을 생성한다.
function isThisCool(vals, fn, rx) {
vals = vals || Array.prototype;
fn = fn || Function.prototype;
rx = rx || RegExp.prototype;
return rx.test(
vals.map(fn).join("")
);
}
isThisCool(); // true
isThisCool(
["a", "b", "c"],
function(v) {
return v.toUpperCase();
},
/D/
); //false
var a = function() {
return "abc";
}
// a.prototype이 생성됨