SoFunction
Updated on 2025-04-10

How to create an object in javascript

JS is an object-based language that can simulate object-oriented languages ​​such as JAVA|C++ using object-oriented ideas.
•Process-oriented
◦Follow the steps to solve the problem

•Object-oriented
◦Focus on the objects (content and roles) needed to solve the problem, and then call relevant methods according to certain rules according to business logic.

Objects are divided into system objects and custom objects. We can create system objects by calling the system constructor, such as array|date, etc. Custom objects must be created by themselves and cannot be created using system functions.

javascript create object

1. Create directly

 //Create directly     //JS creates an object     //1: Create an empty object         var person1 = new Object();
     //2: Add the required properties and methods of this object into          ="ailer" ;
         console .log();
          = "male";
     //3: Method to add this object|(function)         person1. manager= function (){
           console .log("Ailer is my English name" );
        }
     //4: Calling object method: object. method name();         ();

     //Function|Method?  When a function belongs to an object, the function belongs to the method under this object; the function is called by the method name;     //Variable|Properties?  When a variable belongs to a certain object, the variable is the method under this object.  Call variables by attribute names.
      //increase          ="6" ;
      //change          ="lemon" ;
      //check         console .log();
     //delete         delete ;
         console .log();==> undefined

      //Reference type, the address is stored      //Basic type: the value is stored.
     /* var arr1 = [1,2,3,4]
         var arr2 = [5, 6, 7,9];
         var arr2 = arr1;//
         arr2[0]=10;//Change the value in arr2, arr1 also changes
         alert(arr1[0]);//====>10 Reference type*/

        var per2 = new Object();
         = "Relia";
         = "18";
         = "femal";
         = "lemons";

         //1: Access the attribute through. (point syntax)         //2: Access the object's properties through [] (square brackets); square brackets must be attribute strings or variables that save attribute strings | square brackets are used when traversing attributes         var n = "name"
         //(per2["name"]);//Double quotes
         console .log(per2[n]);
         for ( var property in per2) {
//          (per2[property]);
         }

Although intuitive, the code is redundant when creating multiple objects

2. Create using functions (factory mode)

To solve the problem of multiple similar object declarations, we can use a method called factory pattern, which is to solve the problem of instantiating objects with a large number of duplications.

//Define the constructor function createPerson ( name, age) {
//Create a new empty object           var person = new Object;
//Add attributes|Method            = name;
            = age;
           person. manager = function() {
              console .log("ai" );
           }
//return           return person;
        }

         var per1 = createPerson( "ailer", 12 );
         console .log();

        var per2 = createPerson( "lemon", 23 );
        console .log();
        (per2 instanceof Object);//true
        (per2 instanceof createPerson);//false//The object type cannot be distinguished        (==);//false can be obtained by per1 and per2 opening and closing spaces.

Excellent: Bulk creation of similar instances
Missing: The instance uses similar attributes, causing memory waste to be public and the type of the object cannot be distinguished.

3. Literal creation

Excellent: Simple and direct
Missing: Unable to build similar objects in batches

//The object created by literals does not point to the instance using the constructor attribute, but to the object //Create using literals       var per1 = {
        name:"Ailer",
         constructor:per1,
        age:12,
        gender:"female",
        hobby:"play",
        eat:function(){
          ();
        }
       }
       ();//ailer
       ="lemon";
       ();//lemon
       (typeof per1);//Object
       (==Object);//true

4. new+constructor

//The constructor creates an object, and its child objects are not recognized by instanceof. All are created using new+obj        //Objects are identified, but some code area is still wasted; ==>Produce prototype creation        //Create js object new+constructor        //1: Create a constructor | Usually the initial letter is capitalized        function CreatePerson( name , age){
          //2: Affix the object's attributes|method on this pointer. When the function is called to create an object, this pointer points to this new object;          //This is added to this object           = name;
           = age;
          /* = function(){
             //Here this also points to creating an object
             (+" hello");
           }
         }

       /* = "20";
        . ea = function(){
           console .log(+ "sfd" );
        }*/

// __proto__: is: the prototype attribute in the instance object, pointing to the prototype object corresponding to the corresponding constructor//      [[prototype]]
        //Call        var per1 = new CreatePerson( "ailer", "20" );
        var per2 = new CreatePerson( "relia", "18" );
        console .log(per1 instanceof CreatePerson); //==true
        console .log(per2 instanceof CreatePerson); //==>true
        console .log(== ); //==false means that the system has opened up two different code areas, causing memory waste.

It is more convenient to create a literal, so it generates a constructor, a normal constructor (factory pattern), and the sub-object instanceof is not recognized and memory is wasted. Use new+ constructor, and the sub-object is recognized, but some code is still duplicated, memory is wasted, and prototype code is generated to solve it.

5. Prototype mode

      function CreateAnimal(name, age) {
        //1.2: Bind external parameters to instance properties         = name;
         = age;
      }
      //1.3 Bind the same attributes on the prototype (prototype attributes, prototype methods)       = "male";
       = function() {
        ( + " ailers");
      };
      //2: Call the constructor to create an object      var cat1 = new CreateAnimal("xiaohua", "2");
      var cat2 = new CreateAnimal("xiaohua", "2");
      ();

      (==);//The method references the address, put the attributes into the prototype object to save the address
      //Instanceof can determine which object belongs to [function]      //Constructor builder can also be used to determine which object belongs to [constructor] [constant]      //The instance object saves a constructor attribute pointing to its constructor function      //Instanceof and constructor Difference      (cat1 instanceof CreateAnimal);//true
      (cat1 instanceof Object);//true

      ( == CreateAnimal);//true
      ( == Object); //==false

      //The prototype of the constructor also has the constructor attribute that refers to the constructor function      ( == CreateAnimal);//true

      //in determines whether the property exists in this object. This property is an instance property or prototype//           alert("name" in cat1)//true
//           alert("gender" in cat1);//true

      //hasOwnProperty: to determine whether a property is an instance property or inherited from the prototype property if it is true, else does not exist|does not return false;      (("aaa"));//false The non-existent property returns to false      (("name"));//true instance attribute      (("style"));//false The prototype property returns to false
      //Travel the properties to find prototype properties
      //Judge whether the parameters are prototype properties Tool class      (isPrototype("gender", cat1));//true
      function isPrototype(proString, obj) {
        if(proString in obj) {
          if(!(proString)) {
            return true;
          } else {
            return false;
          }
        } else {
          return false;
        }
      }
      /*
 function isProperty(object, property) {//Judge whether there are properties in the prototype
  return !(property) && (property in object);
 }*/

Dynamic Prototype Mode

//Initialize the prototype in the constructorfunction per(name, age, gender) {
         = name;
         = age;
         = gender;
        //Execute only once when initializing the prototype        if(typeof  != "function") {
           = function() {
            alert();
          }
        }
      }

The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.