7/12/2013
2:36:00 PM 0

Javascript Wrapper Object

Javascript 有五個基本型別(primitive types)

string
number
boolean
null
undefined

除了這五個之外, 其他都是物件(object)
去掉 null 及 undefined, 其他三個各有對應的 wrapper 物件

string --> String
number --> Number
boolean --> Boolean

Javascript 在執行過程中可以彈性化的轉換基本型別到相對應的 wrapper 物件
var a = "123";
console.log(typeof a);
a.test = "456";
console.log(a.test);
output
--------------------------------------------
string
undefined
因為是基本型別無法賦予屬性, 所以 a.test 會顯示 undefined

自動轉型成 String 物件
var b = "456";
console.log(b.length);
output
--------------------------------------------
3

如果要自訂屬性則必須使用 wrapper 物件
var obj = new String("test");
obj.test1 = "test wrapper object";
console.log(obj.test1);
console.log(typeof obj);
output
--------------------------------------------
test wrapper object
object

模擬 String 物件內部的操作方式
var obj = {
  "0" : "t"
  "1" : "e"
  "2" : "s"
  "3" : "t"
  length: 4
  test1: "test wrapper object"
}

再來看看 Number 物件
var x = 99;
var y = new Number(99);
console.log(typeof x);
console.log(typeof y); 
console.log(x == y); 
console.log(x === y);
output
--------------------------------------------
number
object
true
false

比較 x == y 時,會呼叫 valueOf() 取得回傳值,並做比較的動作
var s1 = new String("abc");
var n1 = new Number(111);
var b1 = new Boolean(true);
console.log(s1 == "abc");
console.log(n1 == 111);
console.log(b1 == true);
String.prototype.valueOf = function() { return "xyz";}
Number.prototype.valueOf = function() { return 999;}
Boolean.prototype.valueOf = function() { return false;}
console.log(s1 == "abc");
console.log(n1 == 111);
console.log(b1 == true);
console.log(s1.toString());
console.log(n1.toString());
console.log(b1.toString());
output
--------------------------------------------
true
true
true
false
false
false
abc
111
true

0 comments:

Post a Comment