DIV CSS 佈局教程網

JScript 中值型別的裝箱與拆箱
編輯:關於JavaScript     

JScript 物件的 expando 屬性,是為 Object、Array 等參考型別動態增加成員的重要手段。但這招用在值型別上就不管事了,例如:

var str = "string1";
str.method1 = function(){
// do something
};

str.method1(); // 這裡會出錯,提示 str 不存在該方法

在 C# 中,值型別有裝箱(boxing)與拆箱(unboxing)機制,能把它轉成參考型別來處理。JScript 同樣有所謂的值型別,所以我們也可以做類似的事情。實作如下(其中 toJSON() 的作用是把物件以字串形式表示出來,以便用 eval 還原):

Boolean.prototype.box = function(){
    return new Boolean( this );
};
Number.prototype.box = function(){
    return new Number( this );
};
String.prototype.box = function(){
    return new String( this );
};
Boolean.prototype.unbox = function(){
    return eval( this.toJSON() );
};
Number.prototype.unbox = function(){
    return eval( this.toJSON() );
};
String.prototype.unbox = function(){
    return eval( this.toJSON() );
};

box 即裝箱,unbox 即拆箱。測試程式碼:

str = true.box();
alert( str );
str = str.unbox();
alert( str );

如此一來,JScript 也有了裝箱操作。好處是什麼?回到開頭那段語句——現在我們可以像對待 Object 一樣對待 String、Boolean、Number 這三種值型別,在執行期為值型別變數加上 expando 屬性,是不是方便多了?而拆箱也很簡單,呼叫 str.unbox() 即可。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved