Home  >  Article  >  Web Front-end  >  A brief discussion on why strings in JavaScript have methods_javascript skills

A brief discussion on why strings in JavaScript have methods_javascript skills

WBOY
WBOYOriginal
2016-05-16 15:41:591173browse

Introduction

We all know that JavaScript data types are divided into two categories, basic types (or primitive types) and reference types.

Basic type values ​​are simple data segments stored in stack memory, and they are accessed by value. There are five basic types in JS: Undefined, Null, Boolean, Number and String.

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

Objects have properties and methods, so it is not surprising at all 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). This is as natural as eating ice cream in summer. However, look at the code below and think about it carefully, is this and 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 heartbroken girl who willfully executed the "substring" method on a string used to break up, and then happily fell asleep watching the edited version. But, but, isn't it said that string is a basic type? Why can it have methods? ? Is there any royal method, Lord Qingtian?

Actually, all this is because of something called "Basic Packaging Type". This basic packaging type is particularly upright, and is the real "getting done and leaving, hiding the merits and fame"!

Basic packaging types

In addition to the Object, Array and other reference types mentioned at the beginning, JavaScript also provides us with three special reference types: String, Number and Boolean, which facilitates us to operate the corresponding basic types.

Continuing to look at the above example of clipping a string, have you noticed that despite using the substring method, the value of realMessage itself will not change. Calling this method just returns a new string.

This is what the basic packaging type does. Originally you don't have a method, but when you want to use a method, just adjust it. The corresponding basic packaging type has this method. For example, the substring method above is impossible for the basic type string to have this method, but the packaging type String does, and it will execute the method and return the result. When executing to:

realMessage.substring(5,15)

A lot is happening with this line of code.

First, it reads the value of realMessage from memory. When in this reading mode, the background starts to work. JS elevation describes these actions completed in the background like this:

1. Create an instance of String type;
2. Call the specified method on the instance;
3. Destroy this instance

The above example can be illustrated with code like this:

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

So, we understand that it is not the basic type string that executes its own method, but the background creates a corresponding basic packaging type String for it, which instantiates an instance based on the value of the basic type, so that This instance calls the specified method and finally destroys itself, which is amazing.

Pay attention to the "destructible" feature of the basic packaging type in the last step, which determines that we cannot add custom properties and methods to basic type values.

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

I added the age attribute to the string "me" and set the value to a wonderful 18 years old. However, when I visited it again, there was no trace of this attribute. This is because:

When the attribute assignment in the second line of code is executed, an instance of the basic packaging type is created in the background. The age attribute is indeed attached to the instance, but then the instance is destroyed. When the third line of execution is executed, a new instance of the basic packaging type is re-created, which naturally has no age attribute.

Display using basic packaging type

In addition to when the string is in reading mode, the background will help us create basic packaging type instances, and we can also create them explicitly ourselves.

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

This is different from what is saved in the variable when the background helps us create it.

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

Summary

Thanks to the basic packaging types, it is more convenient for us to operate the three basic types of string, boolean, and number. Whenever these three basic types of values ​​are read, the corresponding packaging type instance will be created in the background. This instance will call the specified method and will be destroyed after the call. This short life cycle determines that we cannot add custom properties and methods to basic types.

Let’s take a look at the subString() method and slice() method of the String class in JavaScript

Recently, I was reading the book "Advanced Programming with Javascript" and found some practical skills and knowledge points that I had never encountered before. I wanted to record them on my blog to deepen my memory.

In Section 2.8.4 of the book, we talked about the subString() method and slice() method in the String class. Their usage and return results are basically the same, as shown in the following example:

var strObj = new String("hello world");
alert(strObj.slice(3));      // 输出结果:"ol world"
alert(strObj.subString(3));    // 输出结果:"ol world"
alert(strObj.slice(3, 7));    // 输出结果:"lo w"
alert(strObj.subString(3,7));   // 输出结果:"lo w"

由以上代码的输出结果可已看出,slice()方法和subString()方调用方法法和输出结果完全一样,这两种方法返回的都是要处理的字符串的子串,都接受一个或两个参数,第一个参数是要获取的子串的起始位置,第二个参数是要获取子串的终止位置,如果第二个参数省略终止位置就默认为字符串的长度,且两个方法都不改变String对象自身的值。

为什么有两个功能完全相同的方法呢?事实上,这两个方法并不完全相同,不过只在参数为负值时,他们处理参数的方式稍有不同。

对于负数参数,slice()方法会用字符串的长度加上参数,subString()方法将其作为0处理,例如:

var strObj = new String("hello world");
alert(strObj.slice(-3));      // 输出结果:"rld"
alert(strObj.subString(-3));    // 输出结果:"hello world"
alert(strObj.slice(3,-4));     // 输出结果:"lo w"
alert(strObj.subString(3,-4))   // 输出结果:"hel"

这样既可看到slice()和subString()方法的主要不同。当只有参数-3时,slice()返回"rld",subString()则返回"hello world"。这是因为对于字符串"hello world",slice(-3)将被转换成slice(8),而subString(-3)则转化成subString(0)。同样,使用3和-4差别也是很明显。slice()方法将被转换成slice(3,7),与前面的例子相同,返回"lo w"。而subString()方法则将这个两个参数解释为subString(0,3),实际上是:subString(0,3),因为subString()总是把较小的参数作为起始位,较大的数字最为终止位。

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn