The expando attribute of objects in JScript is an important means of adding members to reference types such as Object and Array, but this method does not work for value types, such as
var str = "string1";
str.method1 = function(){
//do something
};
str.method1();//There will be an error here. The error message (I forgot) is that if str does not exist,
such a statement will not run. In C# programming, there are boxing and unboxing operations for value types. to convert it into a reference type. For this, there are also value types in JScript. We can also do a similar operation. The implementation is as follows. The operation of toJSON() is shown here. Its function is to convert the object (generally speaking) into a character. String representation so that the object can be restored using the eval function.
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 means boxing, unbox means unboxing. The test code is as follows:
str = true.box();
alert(str);
str = str.unbox();
alert( str ); At this point, our JScript also has boxing operations. What are the benefits of this? Let’s look at the statement at the beginning again. At this time, we can treat the three value types of String, Boolean, and Number just like Object. We can add the expando attribute to the value type variables at runtime. Isn’t this very convenient? ?
The unboxing operation is also very simple, just call something like str.unbox().