Home > Web Front-end > JS Tutorial > Introduction to Primitive object encapsulation in JavaScript_javascript skills

Introduction to Primitive object encapsulation in JavaScript_javascript skills

WBOY
Release: 2016-05-16 16:23:00
Original
1181 people have browsed it

In JavaScript, string, number, and boolean are all primitive types, that is, strings, numbers, and Boolean values ​​do not exist in the form of objects. However, since these three primitive types of values ​​need to be operated on, JavaScript will automatically encapsulate these three types of values ​​and make them as objects with properties and methods. Taking string as an example, this encapsulation process is as follows:

1. When JavaScript encounters attribute access or method invocation of a string value, it will call new String (string value) to automatically encapsulate the string into a String object.
2. JavaScript will access the properties or methods of this newly created object and return the corresponding results.
3. After the attribute access or method call is completed, JavaScript will immediately destroy the newly created object.

Taking the following code as an example, it makes no sense to write properties to a String object automatically created by JavaScript, because the created object no longer exists after the writing statement ends:


Copy code The code is as follows:

var s = "test";
s.length = 9;
console.log(s.length);//still 4
s.newVariable = 9;
console.log(s.newVariable);//undefined
console.log(s === "test");//true

It is worth noting that the s variable in the above code always represents a primitive string. The string object automatically created by JavaScript exists in the process of executing the s.length or s.newVariable operation. This can be verified from the last line of code in the above experiment.

In addition to automatically encapsulating Primitive values, developers can also choose to perform the corresponding process manually. Unlike automatic encapsulation, the object obtained by manual encapsulation will not be destroyed immediately, so the property writing operation taken for the manually encapsulated object is meaningful:


Copy code The code is as follows:

var t = new String("test");
t.length = 9;
console.log(t.length);//still 4, as length attribute is read only
t.newVariable = 9;
console.log(t.newVariable);//9

console.log(t == "test");//true
console.log(t === "test");//false

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