Home > Article > Web Front-end > In-depth understanding of js wrapper classes
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);
?
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
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, */
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!