javascript wrapped object instance analysis

  • 2020-05-19 04:14:41
  • OfStack

This article illustrates the use of javascript wrapped objects as an example. Share with you for your reference. The specific analysis is as follows:

The js object is a composite value: it is an attribute or named set of values.

Refer to the following code:


var s = "hello world";
var len = s.length;

In this case, s is a string, and a string is not an object, but why would it have a property? In fact, as long as the string s property is referenced, js will convert the string into an object by calling new String(s), which inherits the string method and is used to handle the property reference. Once the property reference ends, the newly created object is destroyed. (the temporary object is not necessarily created or destroyed by the implementation, but it appears to be.)

Like string 1, Numbers and bores have their own methods: a temporary object is created through the Number() single-core Boolean() constructor, from which the methods are called; However, null and undefined do not wrap objects: accessing their properties causes a type error.
For example, the following code:


var s0 = "hello world";
s0.len = 100;
var t = s.len; //t The value of the will undefined

Because when line 2 creates a temporary object, it is destroyed immediately. Line 3 creates a new string object from the original string value and attempts to read its len property, which naturally does not exist. This code shows that when reading a string, number, and Boolean property value or method, it behaves like object 1. But if you try to assign a value to its property, you ignore this: the change only happens on a temporary object that does not persist.
Creating a temporary object temporarily while accessing properties of a string, number, or Boolean is called a wrapper object.
We can display create a string object and then add its properties, and naturally this property will remain:


var str = "hello world";
var objs = new String(str);
objs.len = 100;
var t = objs.len; //t Will be assigned to zero 100

js converts the wrapper object to its original value when necessary so that the created object and its corresponding original value are often, but not always, represented as one. The == operator treats the original value and its wrapper object as equal; But the === congruent operator treats them as unequal; In addition, you can see the difference between the original value and the wrapped object through the typeof operator.

I hope this article has helped you with your javascript programming.


Related articles: