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

What are the basic knowledge points of JavaScript object

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

Share

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

This article will share with you what the basics of JavaScript objects are. The editor thinks it is very practical, so share it with you as a reference and follow the editor to have a look.

1. Basic 1.1 types of objects

JavaScript has six main language types:

String, number, boolean, undefined, null, object

Base type: the string,number,boolean,undefined,null; base type itself is not an object.

Null

But null is sometimes treated as an object and typeof null returns object. In fact, null is the basic type. The reason is that different objects are represented as binary at the bottom. In JavaScript, if the first three binary bits are 0, they will be judged as object type, and null represents all zeros, so object will be returned when typeof.

Special object subtype array

Arrays are also a type of objects with some additional behavior. Arrays are organized in a more complex way than normal objects.

Function

Functions are essentially the same as ordinary functions, except that they can be called, so they can operate like objects.

1.2 built-in object

String

Number

Date

Boolean

Object

Function

Array

1.3 content

.an is called attribute access, and ['a'] is called operator access.

/ / the property name in the object is always the string myobj= {} myobj [myobj] = 'bar'// assignment myobj [' [object object]'] / / 'bar'1.4 computable property name

Es6 adds computable attribute names. You can use [] to wrap an expression as an attribute name in literal form.

Var perfix = 'foo'var myobj= {[perfix +' bar']: 'hello'} myobj [' foobar'] / / hello1.5 attribute descriptor

Starting with es5, all attributes have attribute descriptors, such as you can directly determine whether the attribute is readable or writable.

/ * * important function: * Object.getOwnPropertyDescriptor (..) / / get property descriptor * Object.defineProperty (..) / / set property descriptor * / writeble (readability) configurable (configurability) enumerable (enumerability) 1.6 iterations through for in

For in can be used to traverse the list of enumerable properties of an object (including the [[Prototype]] chain), and you need to get the property values manually. You can traverse arrays and ordinary objects

For of

Es6 is added, which can be used to traverse the property values of an array. The for of loop first requests an iterator object from the accessed object, and then iterates through all the return values by calling the iterator object's next () method.

The array has a built-in @ @ iterator

How does for of work? Var arr = [1,2,3] var it = arr [Symbol.iterator] () / / iterator object console.log (it.next ()); / / {value: 1, done: false} console.log (it.next ()); / / {value: 2, done: false} console.log (it.next ()); / / {value: 3, done: false} console.log (it.next ()) / / {value: undefined, done: true} / * * use the Symbol.iterator of es6 to get the iterator internal properties of the object. * @ @ iterator itself is not an iterator object, but a function that returns an iterator object. How does the * / object build @ @ iterator to traverse the value of the property?

The for cannot be completed automatically because the object does not have a built-in @ @ iterator. Of traversal. However, you can give you any object definition you want to traverse @ @ iterator, for example:

Var obj= {avell 1 and Symbol.iterator 2} Object.defineProperty (obj, Symbol.iterator, {enumerable: false, writable: false, configurable: true) Value: function () {var self = this var idx = 0 var ks = Object.keys (self) return {next: function () {return {value: Self [KS [IDX + +]] Done: (idx > ks.length)}}) / / manually traverse var it = obj [Symbol.iterator] () / / iterator object console.log (it.next ()) / / {value: 1, done: false} console.log (it.next ()); / / {value: 2, done: false} console.log (it.next ()); / / {value: undefined, done: true} / / for of traversal for (const v of obj) {console.log (v) } / / 2 / / 3 other array traversal functions / * forEach: traverses all and ignores the return value some: runs until the callback function returns true (or "true" value) every: until the callback function returns false (or "false" value) map: filter: returns the conditional value reduce: some is similar to the break statement of every and for Will terminate traversal * / 2, mixed object interview question 1, deep copy and shallow copy of related knowledge basic types and reference types of objects

As mentioned above, there are six main language types of JavaScript: string, number, boolean, null, undefined, object;, of which the first five are basic types, and the last object is a reference type.

Storage of JavaScript variables: stack (stack) and heap (heap)

Stack: automatically allocates memory space and is automatically released by the system, where values of basic types and addresses of reference types are stored

Heap: dynamically allocated memory that varies in size and is not automatically released. It stores the value of the reference type

The biggest difference between a basic type and a reference type is the difference between passing values and addresses.

The basic type is passed by value; the address (pointer) used by the reference type is passed, which assigns the address stored in the stack memory to the received variable.

What are shallow copies and deep copies?

Shallow copy: a shallow copy of an object that copies the 'master' object, but does not copy the objects in the object.' The object inside is shared between the original object and its copy.

Deep copy: a deep copy of an object, not only copying the attributes of the original object one by one, but also recursively copying the objects contained in the attributes of the original object to the new object in turn, so the modification of one object does not affect the other.

For example:

Var anotherObject= {b: "b"} var anotherArray= [] var myObject= {a b:anotherObject, / / reference, not a copy c:anotherArray / / another reference} anotherArray.push (anotherObject,myObject) / * how to accurately copy myObject? Shallow copy myObject, that is, copying the value of an in the new object will copy the value of an in the object, that is,'a', but the two properties of b and c in the object are actually only three references, and the b and c properties of the new object are the same as those of the old object. A deep copy of myObject replicates anotherObject and anotherArray in addition to myObject. But there is a problem with copying myObject deeply. AnotherArray references anotherObject and myObject, so you need to copy myObject, which will lead to an endless loop due to circular references. How to deal with this situation will be described later. * / how to implement shallow copy object

Object.assign (), extension operator (… )

Var obj1 = {x: 1, y: 2} var obj2 = Object.assign ({}, obj1); console.log (obj1) / / {x: 1, y: 2} console.log (obj2) / / {x: 1, y: 2} obj2.x = 2 / / modify obj2.xconsole.log (obj1) / / {x: 1, y: 2} console.log (obj2) / / {x: 2, y: 2} var obj1 = {x: 1, y: {m: 1}}; var obj2 = Object.assign ({}, obj1) Console.log (obj1) / / {x: 1, y: {m: 1}} console.log (obj2) / / {x: 1, y: {m: 1}} obj2.y.m = 2; / / modify obj2.y.mconsole.log (obj1) / / {x: 1, y: {m: 2}} console.log (obj2) / / {x: 2, y: {m: 2}} Array

Slice (), concat, Array.from (), extension operator (... ), concat, for loop

Var arr1 = [1,2, [3,4]], arr2 = arr1.slice (); console.log (arr1); / / [1,2, [3,4]] console.log (arr2); / / [1,2, [3,4]] arr2 [0] = 2 arr2 [2] [1] = 5; console.log (arr1); / / [1,2, [3,5]] console.log (arr2) / / [2,2, [3,5]] how to implement deep copy JSON.parse (JSON.stringify (obj))

During JSON.stringify () serialization, undefined, arbitrary functions, and symbol values are ignored during serialization (when they appear in property values of non-array objects) or converted to null (when they appear in an array).

Var obj1 = {x: 1, y: {m: 1}, a:undefined, b:function (areline b) {return ahumb}, c:Symbol ("foo")}; var obj2 = JSON.parse (JSON.stringify (obj1)) Console.log (obj1) / / {x: 1, y: {m: 1}, a: undefined, b: foo, c: Symbol (foo)} console.log (obj2) / / {x: 1, y: {m: 1}} obj2.y.m = 2 / / modify the simple implementation of obj2.y.mconsole.log (obj1) / / {x: 1, y: {m: 1}, a: undefined, b: foo, c: Symbol (foo)} console.log (obj2) / / {x: 2, y: {m: 2}} Deep copy function function deepClone (obj) {let result = Array.isArray (obj)? []: {} If (obj & & typeof obj = "object") {for (let key in obj) {if (obj.hasOwnProperty (key)) {if (obj [key] & & typeof obj [key] = "object") {result [key] = deepClone (obj [key]);} else {result [key] = obj [key];} return result } var obj1 = {x: {m: 1}, y: undefined, z: function add (Z1, Z2) {return Z1 + Z2}, a: Symbol ("foo"), b: [1 null], c: null}; var obj2 = deepClone (obj1); obj2.x.m = 2 × obj2.b [0] = 2 x console.log (obj1); console.log (obj2) / obj1 {a: Symbol (foo) b: (5) [1, 2, 3, 4, 5] c: nullx: {m: 1} y: add (z1, z2)} / / obj2 {a: Symbol (foo) b: (5) [2, 2, 3, 4, 5] c: nullx: {m: 2} y: undefinedz: add (z1, z2)}

The deep copy method above encounters a circular reference and falls into a recursive process of a loop, resulting in a stack explosion. So it needs to be improved.

Improvement of deep copy function (to prevent loop recursion)

To solve the problem of breaking the stack due to loop recursion, you only need to determine whether the field of an object refers to the object or any parent of the object.

Function deepClone (obj, parent = null) {/ / improved (1) let result = Array.isArray (obj)? []: {}; let _ parent = parent; / / improved (2) while (_ parent) {/ / improved (3) if (_ parent.originalParent = obj) {return _ parent.currentParent;} _ parent = _ parent.parent } if (obj & & typeof obj = "object") {for (let key in obj) {if (obj.hasOwnProperty (key)) {if (objkey] & & typeof obj [key] = "object") {result [key] = deepClone (obj [key], {/ / improved (4) originalParent: obj, currentParent: result, parent: parent}) } else {result [key] = obj [key];} return result;} / / debugging var obj1 = {x: 1, y: 2}; obj1.z = obj1;var obj2 = deepClone (obj1); console.log (obj1); console.log (obj2) Deep copy function final version (supports basic data types, prototype chain, RegExp, Date types) function deepClone (obj, parent = null) {let result; / / final return result let _ parent = parent; / / prevent circular reference while (_ parent) {if (_ parent.originalParent = obj) {return _ parent.currentParent;} _ parent = _ parent.parent } if (obj & & typeof obj = = "object") {/ / returns the reference data type (null has been excluded by the judgment condition) if (obj instanceof RegExp) {/ / RegExp type result = new RegExp (obj.source, obj.flags)} else if (obj instanceof Date) {/ / Date type result = new Date (obj.getTime ()) } else {if (obj instanceof Array) {/ / Array type result = []} else {/ / Object type, inheriting prototype chain let proto = Object.getPrototypeOf (obj); result = Object.create (proto) } for (let key in obj) {/ / Deep copy if (obj.hasOwnProperty (key) of Array type and Object type) {if (OBJ [key] & & typeof obj [key] = "object") {result [key] = deepClone (obj [key], {originalParent: obj, currentParent: result, parent: parent}) } else {result [key] = obj [key];}} else {/ / returns the basic data type and Function type, because Function does not need a deep copy of return obj} return result } / / for debugging function construct () {this.a = 1, this.b = {x return 2, YRV 3, z: [4je 5, [6]]}, this.c = [7je 8, [9 J 10]], this.d = new Date (), this.e = / abc/ig, this.f = function (a Jing b) {return adepb}, this.g = null This.h = undefined, this.i = "hello", this.j = Symbol ("foo")} construct.prototype.str = "Ihumm prototype" var obj1 = new construct () obj1.k = obj1obj2 = deepClone (obj1) obj2.b.x = 999obj2.c [0] = 666console.log (obj1) console.log (obj2) console.log (obj1.str) console.log (obj2.str)

Note: deep copy of Function type:

Bind (): use fn.bind () to make a deep copy of the function, but cannot use it because the this pointer points to a problem

Eval (fn.toString ()): only the arrow function is supported, but the ordinary function function fn () {} is not applicable.

New Function (arg1,arg2, … , function_body): parameters and function bodies need to be extracted

Thank you for reading! This is the end of this article on "what are the basic knowledge points of JavaScript objects?". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, you can share it for more people to see!

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