Home > Web Front-end > JS Tutorial > In-depth understanding of js wrapper classes

In-depth understanding of js wrapper classes

零到壹度
Release: 2018-04-12 11:21:29
Original
2727 people have browsed it

The content of this article is to share with you an in-depth understanding of the js packaging class. It has a certain reference value. Friends in need can refer to it.

Let’s read it before talking about the packaging class. What is the answer to the following example

var str = 'hello';
str.name = 'world';
console.log(str.name);
Copy after login

?

Isn’t this obvious? The str above has added an attribute named name and the value is world. The output must be world!

I think when you see this code, this is the first thing that comes to mind!

Congratulations, you got the answer wrong! The value is undefined!

We know that in js, except for original values, everything else is an object, and objects can have their own properties and methods. (The method is when the attribute is a function, we call it a method)

So does the original value have its own attributes?

var str = 'hello';
console.log(str.length) // 6
Copy after login

The method we call the string length can be combined with the array His number is also printed out.

Since strings are not objects, why do they have their own methods?

This is because as long as we use the str attribute, js will call new String(str) to wrap str into an object. This object inherits the method above String.


#These are all String methods.

But what if there is no attribute you want on String?

Then js will create an attribute on String, but after creation, it will be destroyed immediately.

Let’s look at this example again

var str = 'hello';
str.name = 'world'; 
/*
上面这一步str给他自己设置一个名为name,值为world的属性,于是js就new String(str).name = 'world';
创建之后,销毁
*/
console.log(str.name)
/*
这一步 js又new String(str).name 但是没有值,
所以值为undefined,
*/
Copy after login

Similarly, number and boolean are also

The above is the detailed content of In-depth understanding of js wrapper classes. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template