JScript中值类型的封箱与拆箱


JScript中对象的expando属性是对Object,Array等引用类型增加成员的一种重要手段,但这种手段在对值类型时就不行了,比如
var str = "string1";
str.method1 = function(){
//do something
};

str.method1();//这里将出错,错误信息(我忘记了)是说str不存在该方法

这样的语句就会运行不了,而在C#编程中值类型存在装箱与拆箱操作来将其转换为引用类型,对此,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()就搞定。

 

本文作者:
« 
» 
快速导航

Copyright © 2016 phpStudy | 豫ICP备2021030365号-3