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
Summarize 1. Similarities Both can change the int...
1 Problem description: 1.1 When VMware is install...
Table of contents Controller type of k8s Relation...
Preface In some cases, we only know the intranet ...
Table of contents tool: Login scenario: practice:...
There is a table user, and the fields are id, nic...
I'll record my first attempt at vue3.0. When ...
Table of contents Preliminary Notes Problem Repro...
The default operating mode of MySQL is autocommit...
As shown below: LOCATE(substr,str) Returns the fi...
Recently the company has arranged to do some CCFA...
need: In background management, there are often d...
Dataframe is a new API introduced in Spark 1.3.0,...
It is mainly the configuration jump of the if jud...
Table of contents 1. Background knowledge 1. Intr...