Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Introduction to the original value of JavaScript and Packaging object

2025-04-01 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article mainly introduces "the introduction of JavaScript original value and packaging object". In daily operation, I believe that many people have doubts about the introduction of JavaScript original value and packaging object. Xiaobian consulted all kinds of materials and sorted out simple and easy-to-use operation methods. I hope it will be helpful to answer the doubts of "JavaScript original value and packaging object introduction". Next, please follow the editor to study!

Preface

As JavaScript becomes more and more popular, more and more developers are coming into contact with and using JavaScript.

At the same time, I also found that many developers do not have a clear understanding of the most basic raw values and wrapper objects of JavaScript.

So in this article, dregs will introduce them to you in detail.

Don't say much, Let's go!

Text

Original type (Primitive types)

The primitive type is also called the "basic type".

There are currently several primitive types in JavaScript:

String (string)

Number (digital)

Boolean (Bull)

Null (empty)

Undefined (undefined)

Bigint (large integers, ES6)

Symbol (logo? ES6)

As follows:

Typeof 'chenpipi'; / / "string" typeof 12345; / / "number" typeof true; / / "boolean" typeof null; / / "object" typeof undefined; / / "undefined" typeof 12345n; / / "bigint" typeof Symbol (); / / "symbol"

Pay special attention to

Typeof null returns "object", but this does not mean that null is an object, it is actually a Bug of JavaScript, and it has been so since JavaScript was born.

In the original implementation of JavaScript, the value in JavaScript was represented by a label representing the type and the actual data value. The type label of the object is 0. Because null represents a null pointer (the value is 0x00 on most platforms), the type label of null is 0memery type of null and therefore returns "object".

The history of "typeof null": https://2ality.com/2013/10/typeof-null.html

Original value (Primitive values)

The original value is the value of the original type (data).

A primitive value is data that is not an object and has no methods.

The original value is a kind of non-object data without any method.

That is, the values of primitive types such as string, number, and boolean have no properties or methods of their own.

At this time, my little friend with a keen sense of smell has sensed that something is wrong.

It's cumin! I added cumin! (manual dog head and scratch off)

There is a very interesting point here, but before we discuss this issue, let's take a look at the packaging object.

Wrapping object (Wrapper objects)

All primitive types except null and undefined have their corresponding wrapper objects:

String (string)

Number (digital)

Boolean (Bull)

BigInt (large integers, ES6)

Symbol (logo? ES6)

Object (Object)

Object is a reference type.

First of all, the wrapper object itself is an object and a function.

String instanceof Object; / / true String instanceof Function; / / true constructor (Constructor)

Instance (Instance)

String, Number, and Boolean all support the use of the new operator to create corresponding wrapper object instances.

For example, the statement of String (excerpt):

Interface StringConstructor {new (value?: any): String; (value?: any): string; readonly prototype: String;} declare var String: StringConstructor

The data obtained using the new operator is an object (Object):

/ / string typeof 'pp'; / / "string" typeof new String (' pp'); / / "object" new String () instanceof Object; / / true / / numeric typeof 123; / / "number" typeof new Number (123); / / "object" new Number () instanceof Object; / / true / / Boolean typeof true / / "boolean" typeof new Boolean (true); / / "object" new Boolean () instanceof Object; / / true

We can call the valueOf () function that wraps the object instance to get its original value:

/ / string let s = new String ('pp'); s.valueOf (); / / "pp" typeof s.valueOf (); / / "string" / / numeric let n = new Number (123); n.valueOf (); / / 123 typeof n.valueOf (); / / "number" / / Boolean let b = new Boolean (true); b.valueOf () / / true typeof b.valueOf (); / / "boolean"

"alien" (Attention)

BigInt and Symbol are both "incomplete classes" and do not support the new operator.

For example, the statement of BigInt (excerpt):

Interface BigIntConstructor {(value?: any): bigint; readonly prototype: BigInt;} declare var BigInt: BigIntConstructor

You can see that there are no new operator related functions in BigInt's declaration.

Ordinary function (Function)

Wrapper objects can also be used as ordinary functions.

The String (), Number (), and Boolean () functions can all be used to explicitly cast any type of data.

In addition, the Object () function can also be used for explicit type conversions, but this article will not expand.

String

Sample code:

Typeof String (); / / "string" String (); / / "" String ('pp'); / / "pp" String (123); / / "123" String (true); / / "true" String (false); / / "false" String (null); / / "null" String (undefined); / / "undefined" String ([]) / / "" String ({}); / / "[object Object]"

Tip 1

When we use the String () function to convert an object, JavaScript first accesses the toString () function on the object, and if it is not implemented, it looks up the prototype chain.

Take Chestnut: the result returned by executing String ({toString () {return 'pp';}}) is "pp", not "[object Object]".

So the String () function cannot be used to determine whether a value is an object (it will roll over).

Tip 2

The common way to judge an object is Object.prototype.toString ({}) = ='[object Object]'.

For example, chestnut: executing Object.prototype.toString ({toString () {return 'pp';}}) returns "[object Object]".

Number

Sample code:

Typeof Number (); / / "number" Number (); / / 0 Number (''); / / 0 Number ('pp'); / / NaN Number (123); / / 123 Number (true); / / 1 Number (false); / / 0 Number (null); / / 0 Number (undefined); / / NaN Number ([]); / / 0 Number ({}) / / NaN

Tips

Perhaps the most useful transformation for the Number () function is to convert true and false to ones and zeros.

Boolean

Sample code:

Typeof Boolean (); / / "boolean" Boolean (); / / false Boolean (''); / / false Boolean ('pp'); / / true Boolean (0); / / false Boolean (1); / / true Boolean (null); / / false Boolean (undefined); / / false Boolean ([]); / / true Boolean ({}); / / true

Tips

In some cases, we will use 0 and 1 in the data to indicate the true or false state, and we can use Boolean () to determine the status.

BigInt

The BigInt () function is used to convert integers to large integers.

This function takes an integer as an argument, and an error is reported if the argument is a floating-point number or any data of a non-numeric type.

Sample code:

BigInt (123n); / 123n BigInt (123n); / / 123n typeof 123n; / / "bigint" typeof BigInt (123n); / / "bigint"

BigInt & Number

It should be noted that BigInt and Number are not strictly equal (loosely equal).

Sample code:

123n = = 123; / / false 123n = = 123; / / true

Symbol

The Symbol () function creates a value of type symbol.

This function takes a string as a descriptor (parameter), and if you pass in a value of another type, it is converted to a string (except undefined).

Note that each symbol value is unique, even if their descriptors are the same.

And data of type symbol can only be created through the Symbol () function.

Sample code:

/ / the return value is simulated by Devtools, not the actual value Symbol ('pp'); / / Symbol (pp) Symbol (123); / / Symbol (123) Symbol (null); / / Symbol (null) Symbol ({}); / / Symbol ([object Object]) / / Type typeof Symbol (' pp') / / "symbol" Symbol ('pp') = Symbol (' pp'); / / false / / descriptor Symbol ('pp'). Description; / / "pp" Symbol (123) .description; / / "123" Symbol ({}) .description; / / "[object Object]" Symbol (). Description; / / undefined Symbol (undefined) .description; / / undefined

Original value is not an object (Primitive not Object)

Here comes the interesting part.

No properties and methods (No properties, no functions)

As mentioned earlier in this article: "the original value is a kind of non-object data without any method." "

We all know that objects (Object) can have properties and methods.

But a string is not an object, so you can't add attributes to a string.

Do a little experiment:

Let a = 'chenpipi'; console.log (a.length); / / 8 / / try to add a new attribute a.name =' Daniel Wu'; console.log (a.name); / / undefined / / try to modify the existing attribute typeof a.slice; / / "function" a.slice = null; typeof a.slice; / / "function"

Cinnamon Little Theater

At this point, a leading friend uses the rebuttal skill.

Don't fool people here, I usually write Bug, oh, when I don't write code, I can obviously call methods on strings, numbers and Boolean values!

For example, the following code can be executed normally and get the expected results:

/ / string let s = 'chenpipi'; s.toUpperCase (); / / "CHENPIPI"' ChenPiPi'.slice (4); / / "PiPi" / / numeric let n = 123; n.toString (); / / "123" (123.45) .tofixed (2); / /" 123.5 "/ / Boolean value let b = true; b.toString (); / /" true "false.toString () / / "false"

Useless little knowledge

Have you noticed that the function cannot be called directly after the literal quantity of the number? For example, executing 123.toString () will report SyntaxError (syntax error).

This is because the number (floating point) itself uses the decimal point, and the calling function needs to use the decimal point, which leads to ambiguity (strings and Boolean values do not have this worry).

In this case, we can wrap the number in parentheses (), such as (123). ToString (), or use two consecutive decimal points.. To call a function such as 123..toString ().

It's weird.

So if a string is not an object, why does a string have properties and methods?

On second thought, numbers are numbers. How can there be a way in numbers?

This is indeed illogical, but it contradicts reality.

What's going on?

Double messenger (I can't translate this)

The answer is revealed.

Covert operation

In the case of a string (string), when we read the properties or methods of a string in our code, JavaScript silently does the following:

Hongmeng official Strategic Cooperation to build HarmonyOS Technology Community

Create a temporary wrapper object instance by new String ()

Execute our code logic (reading properties or executing functions) through the objects created

Temporary objects are no longer in use and can be destroyed.

Such as the following chestnuts:

Let a = 'chenpipi'; console.log (a); / / "chenpipi" / /-- let b1 = a.length; console.log (b1); / / 8 / / the above code is equivalent to: let b2 = (new String (a)) .length; console.log (b2) / / 8 /-- let C1 = a.toUpperCase (); console.log (C1); / / "CHENPIPI" / / the above code is equivalent to: let c2 = (new String (a)). ToUpperCase (); console.log (c2); / / "CHENPIPI"

Numbers (number) and Boolean values (boolean) are the same, but numbers create temporary objects through new Number (), and Boolean values are created by new Boolean ().

In addition to the above example, the most powerful proof is their constructor:

'chenpipi'.constructor = = String; / / true (12345). Constructor = = Number; / / true true.constructor = Boolean; / / true

All this is done secretly by JavaScript, and the temporary objects generated in the process are all disposable (discarded after use).

I see

Wuhu, that makes sense!

This explains why we can access properties and methods on strings, but not add or modify properties.

That's because the goal of our actual operation is actually the temporary object created by JavaScript, not the string itself!

So our additions or modifications actually take effect, only on temporary objects!

It's like this:

/ / in the code: let a = 'chenpipi'; a.name =' Daniel Wu'; console.log (a.name); / / undefined / / equivalent to: let a = 'chenpipi'; (new String (a)). Name =' Daniel Wu'; console.log (a.name); / / undefined / / equivalent to: let a = 'chenpipi'; let temp = new String (a); temp.name =' Daniel'; console.log (a.name) / / undefined at this point, the study on "introduction to the original value of JavaScript and packaging objects" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report