Home  >  Article  >  Web Front-end  >  Introduction to wrapper objects in JavaScript_javascript tips

Introduction to wrapper objects in JavaScript_javascript tips

WBOY
WBOYOriginal
2016-05-16 16:18:051032browse

JavaScript object is a composite value. It is a collection of attributes or named values. The attribute value is referenced through the symbol ".". When the attribute value is a function, we call it a method. We see that strings also have properties and methods:

Copy code The code is as follows:

var s="hello, world!";
var word=s.substring(s.indexof("") 1,s.length);

Since a string is not an object, why does it have attributes? As long as the attributes of the string s are referenced, JavaScript will convert the string value into an object by calling the constructor of new String(s). This object inherits the properties of the string. method, and is used to handle references to properties. Once the property reference ends, the newly created object will be destroyed (in fact, this object is not necessarily created in the implementation, but the whole process looks like this).

Like strings, numbers and Boolean values ​​also have their own methods: a temporary object is created through the Number() and Boolean() constructors, and the calls to these methods come from this temporary object. This temporary object is called a wrapper object.

Note:

Copy code The code is as follows:

           var s="test";          //Declare a string
​​ s.len=4; Var t = s.Len; // Query this attribute

At this time, when we output t, it should be undefined. The second line of code creates a temporary string object, assigns its len attribute a value of 4, and then destroys the object. The third line of code sets a new one through the original string value s. Attribute, try to read its len attribute. This attribute naturally does not exist, so the value when t is output is undefined.
This code shows that when reading the attribute value (or method) of a number, string, or Boolean value, it behaves like an object, but when trying to assign a value to its attribute, this operation is ignored: the modification just happens on a temporary object that is not retained.

The temporary object created when accessing properties of strings, numbers, or Boolean values ​​is called a wrapper object. It is only occasionally used to distinguish string values ​​and string objects, numbers and numeric objects, Boolean values ​​and Boolean objects

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