Enclosure and unboxing of value types in JScript

Source: Internet
Author: User
Tags eval reference return tojson
Js|jscript

The Expando property of an object in JScript is an important means of adding a member to a reference type such as Object,array, but this is not the case for a value type, such as
var str = "string1";
Str.method1 = function () {
Do something
};

STR.METHOD1 ();//There will be an error, the error message (I forgot) is that STR does not exist in this method

Such a statement would not run, and in C # programming a value type has a boxing and unboxing operation to convert it to a reference type, and for that, there are value types in JScript, and we can do a similar operation, which is implemented as follows, where the operation of Tojson () is shown here, The purpose is to represent objects (generic) in strings, so that the object can be restored using the Eval function.
Boolean.prototype.box = function () {
Return to New Boolean (this);
};
Number.prototype.box = function () {
Return to new number (this);
};
String.prototype.box = function () {
Return a 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 ());
The};box is the packing, the unbox is the unpacking. The test code is as follows:
str = True.box ();
alert (str);
str = Str.unbox ();
alert (str); so we have a boxed operation in JScript, what's the benefit? Take a look at the beginning of the sentence, at this time we can treat String,boolean,number as the object of the three types of value, you can at run time for the variable value type of the Expando property, this is not convenient?
And the unboxing operation is also very simple, only need to call the similar str.unbox () to be done.



Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.