Home >Web Front-end >JS Tutorial >About javascript wrapper type objects

About javascript wrapper type objects

巴扎黑
巴扎黑Original
2016-11-25 11:59:271094browse

Let’s first look at some test codes like this to see what problems we can find:

var str=”likeke”;

str;//”likeke”

str.length;//6

str.age=22 ;

str.age;//undefined;

var mystr=new String("likeke");

mystr;//String {0: "l", 1: "i", 2: "k ", 3: "e", 4: "k", 5: "e", length: 6, [[PrimitiveValue]]: "likeke"}

mystr.length;//6

mystr.age=22 ;

mystr.age;//22

First question: Why can the basic type string access the length attribute?

Second question: The wrapper type of string can access custom attributes, but the basic type Why can't string be accessed?

Reason: 1. When we access a basic type string attribute in the form of an object or create a new attribute for it, the js engine will convert it into the corresponding packaging type object;

          2. When we add a self- After defining the properties, the temporary object will be destroyed immediately. Therefore, accessing this property again (which will also be converted to its wrapping type again) appears as undefind .

In addition to string, other basic types have similar principles, for example, (666).toString().length;//3


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