Why string can have a method in JavaScript?

Source: Internet
Author: User

Introduction

As we all know, JavaScript data types are divided into two major classes, primitive type (or original type) and reference type.

The basic types of values are simple data segments that are stored in the stack memory and are accessed by value. There are five basic types in JS: Undefined, Null, Boolean, number, and string.

The value of a reference type is an object that is stored in heap memory, and its value is accessed by reference. Reference types are mainly object, Array, Function, RegExp, Date.

Objects are owned by properties and methods, so it is not surprising that we see the following code.

var favs=[‘鸡蛋‘,‘莲蓬‘];favs.push(‘秋葵‘);console.log(favs);//["鸡蛋", "莲蓬", "秋葵"]console.log(favs.length);//3

Array is a reference type, so it can naturally have properties (length) and methods (push), which is just like eating ice cream in the summer. But, look at the following code, think about it, is this, legal?

var realMessage="Said I love you but I lied";var myMessage=realMessage.substring(5,15);console.log(myMessage); //"I love you"

There was a broken-hearted woman paper wayward to a string used to break up the "substring" method, and then happily watched the clip version of sleep. But, but, not to say string is the basic type, why it can have a method?? There is no principality AH Sky Big Master!

In fact, all this is because there is a "basic packaging type" of East. This basic packaging type is particularly upright, is the real "thing to brush clothes, deep work and name"!

Basic Package Type

In addition to reference types such as Object, array, and so on, JavaScript provides us with three special reference types: String, Number, and Boolean, which allow us to manipulate the underlying type.

Continue to look at the example of the clip string above, have not noticed that although the substring method is used, the value of the realmessage itself will not change, call this method just return a new string.

This is what the basic packaging type does. Originally you do not have the method, but when you want to use the method, you although the adjustment, the corresponding basic packing type has this method to be OK. For example, the substring method above, the basic type of string is impossible to have this method, but string this wrapper type has ah, it will be chi began popping the method to complete the results returned. In the execution to:

realMessage.substring(5,15)

There's a lot going on with this line of code.

First, it reads the value of the realmessage from memory. When in this reading mode, the background starts to work. JS elevation describes these actions that are done in the background:

1. Create an instance of the string type;
2. Invoke the specified method on the instance;
3. Destroying this instance

The above example can be illustrated with this code:

var _realMessage=new String("Said I love you but I lied");var myMessage=_realMessage.substring(5,15);_realMessgae=null; //方法调用后即销毁

So, so we understand, is not the basic type of string executes its own method, but the background for it to create a corresponding basic wrapper type string, it is based on the value of the basic type of an instance, let this instance to invoke the specified method, and finally destroy themselves, the sense of the sky has wood.

Note The final step the basic wrapper type "destroys" the attribute, which determines that we cannot add custom properties and methods for the base type value.

var me="sunjing";me.age=18;console.log(me.age);//undefined

I added the Age property to the "Me" string, and the value was set to a beautiful 18-year-old, and then the egg, once again visited, this attribute has no trace. This is because:

When you perform the assignment to the second line of code property, the background creates an instance of the basic wrapper type, and the age property is actually attached to the instance, but immediately after that, the instance is destroyed. When you execute to the third row, you re-create an instance of the new basic wrapper type, which naturally does not have an age attribute.

Show use basic wrapper type

In addition to being in read mode, the background will help us create a basic wrapper type instance, which we can also create ourselves.

var str=new String("hello");var str2=str.toUpperCase();console.log(str2);//"HELLO:

This is different from what is stored in the background to help us create the variables.

var str1=new String("hello");var str2="hello";typeof str1 //"object"typeof str2 //"string"
Summarize

Thanks to the basic packing type, it is more convenient for us to manipulate the three basic types of string, Boolean, number. Each time you read the three basic type values, the background creates the corresponding wrapper type instance, which invokes the specified method and is destroyed when the call is finished. This short life cycle determines that we cannot add custom properties and methods to the base type.

Why string can have a method in JavaScript?

Related Article

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.