Wrapper Object--javascript The reason that the original type owns the property

Source: Internet
Author: User

Let's look at the code first:

var s = "Test"; var len=s.length;

We know that the string declared in JavaScript like above is not an object, but since S is not an object, why is there a property of length?

The reason is that in JavaScript, whenever you reference a property of a string (numeric, Boolean, and so on), JS converts the string to an object by calling new string (s), which inherits the string's method and is used to handle the property's reference. Once the attribute reference is finished, the newly created object is destroyed (the real implementation is not necessarily the case, but the whole process looks like this). This process is called the wrapper object.

Is there a way to verify the above explanation, we look at two pieces of code:

Code One:

var s = "Test"; s.len=10;//creates a string object and adds the Len attribute, then destroys var t = s.len;//Creates a string object, reads the Len property, and the result is undefined because it does not exist

Code two:

var s = new String ("Test"); S.len = 10;var T = S.LEN;//10

The last thing to note is that the original object and the wrapper object are not strictly equal:

var s = "Test", S=new String ("test"), console.log (s = = s);//trueconsole.log (s = = = s);//false

Wrapper Object--javascript The reason that the original type owns the property

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.