This is the 13th day of my participation in the August More Text Challenge.More challenges in August

There are many ways to create objects in JavaScript. Here are three to help you understand and expand.

Call the constructor to create the object

The constructor is called to create an object by first creating a constructor and then instantiating an object

var obj = new Object();
Copy the code
Var person = new Object(); Person. Name = "person "; person.age = 23; Person.eat = function () {console.log(" my name "+ this.name + "," +" I love hotpot "); }; person.eat();Copy the code

Factory mode creates objects

Factory mode creates objects, and given that classes cannot be created in ECMAScript, developers invent a function that encapsulates the details of creating objects with a particular interface, as shown in the following example

Function cObj(name,age) {var obj = new Object(); // create object // add attribute obj.name = name; obj.age = age; / / add methods obj. Eat = function () {the console. The log (" my name is "+ this. The name +",,, "+ this. Age +", "+",,, "+" love to eat hot pot "); }; return obj; } // create object var luzp = cObj(" little brother ",27); luzp.eat(); Var lut = cObj("小 sweety ",30); lut.eat();Copy the code

The function cObj() builds an object with all the necessary information based on the parameters it receives. This function can be called countless times, and each time it returns an object containing a method with three properties.

3. Custom constructors create objects

Custom constructors create objects to define custom object properties and methods

Function Person(name,age) {this.name = name; this.age = age; This.eat = function () {console.log(" my name "+ this.age + "," +" we love hotpot "); }; } // create an object var lut = new Person("小 sweet ",23); console.log(lut.name); lut.eat();Copy the code

Note: The custom constructor generates the following four events when creating an object

  • When a new object is created, a space is allocated in memory to store the new object
  • Set this to the current object
  • Sets the values of the properties and methods of the object
  • Return this object

Create objects literally

Var lut={name: "", age: 23, place: "This ", meet:function () {console.log(this.age +" this "+" this "+" this "); }, eat:function () {console.log(" I love hotpot "); }}; lut.meet(); lut.eat();Copy the code