Preface: In 1. Object literalslet obj = {} // empty object let obj2 = {a:1, b:2} let obj3 = {" hel": "wold"} // If the property name has spaces, you can use a string literal as the property name 2. The new keyword creates an object Use the let o = new Object(); // built-in constructor let m = new Math(); let a = new Array(); let d = new Date(); function Person(){ //Custom constructor} let person = new Person() 3. Create an object using Object.create()let o = Object.create({x:1, y:2}); console.log(o.x+oy) //3 The new object o will inherit Object.create(null) 4. Use the extension operator:...ES2018 adds the spread operator ... to copy existing object properties to a new object let foo = {x:1, y:2} let bar = {z:3} let zoo = { ...foo, ...bar} console.log(zoo) // {x:1, y:2, z:3} A few points to note:
5. Use Object.assign() method let foo = {x:1, y:2} let bar = {z:3} let zoo = {} let obj = Object.assign(zoo, foo, bar) console.log(zoo) // {x:1, y:2, z:3} console.log(obj===zoo) // true In addition, two new object features added in 6. Abbreviated propertiesIf you want to create an object composed of multiple variable names and corresponding values, you need to construct the object like the traditional object literal syntax. let x = 1, y = 2; let o = {x:x, y:y} console.log(o) // {x:1, y:2} After let o2 = {x, y} console.log(o2) // {x:1, y:2} 7. Abbreviation method When defining methods in an object, let point = { x:1, y:2, area: function(){ return this.x*this.y } } console.log(point.area()) //2 After let point2={ x:1, y:2, area(){ return this.x*this.y } } console.log(point2.area()) //2 This concludes this article about 3 methods of creating JavaScript objects. For more information about JavaScript object creation methods, please search 123WORDPRESS.COM’s previous articles or continue browsing the following related articles. I hope you will support 123WORDPRESS.COM in the future! You may also be interested in:
|
<<: Introduction to the use of MySQL official performance testing tool mysqlslap
>>: CSS uses radial-gradient to implement coupon styles
XML is designed to describe, store, transmit and ...
Table of contents Skeleton screen use Vue archite...
This article shares the installation and configur...
Table of contents Manual deployment 1. Create a s...
Today I received a disk warning notification from...
In the past few years, DIV+CSS was very popular in...
Using the knowledge of CSS variables, I will dire...
Effect screenshots: Implementation code: Copy code...
This article example shares the specific code of ...
Table of contents 1. Display and hide by default ...
MySQL supports many data types, and choosing the ...
Preface nginx uses a multi-process model. When a ...
W3Cschool explains it this way The <meta> el...
Summary This article will introduce the following...
How to refresh iframe 1. To refresh, you can use j...