Method summary for creating custom objects in Javascript

  • 2020-03-30 04:29:58
  • OfStack

There are many ways to create objects in Javascript.

Object constructor/Object literal :

Design patterns aside, the most basic approach is to call the Object constructor to create an Object and then add properties to the Object.


     var student = new Object();
     student.name = "xiao ming";
     student.age = 20;
     student.getName = function () {
         alert(this.name);
     }

For those of you who are familiar with the literal nature of javascript objects, you can write it a little bit better, or at least look a little bit cleaner.


    var student = {
        name: "xiao hong",
        age: 18,
        getName: function () {
            alert(this.name);
        }
    };

  Cons: the downside of the above approach is that creating many similar objects using the same interface results in a lot of duplicate code. This should be easy to understand, functions (methods or classes) are generally used to create common methods, the above object creation process, there is no shadow of the function, so there is no reuse.

The factory pattern :

The factory pattern abstracts the process of concrete object creation. Like a black box, you just call the function (enter the factory), pass in the corresponding parameters (various raw materials), and out comes the corresponding object (the product produced by the factory). The factory pattern solves the problem of creating multiple similar objects.


     function studentFactory(name,age) {
         var student = new Object();
         student.name = name;
         student.age = age;
         student.sayName = function () {
             alert(this.name);
         }
         return student;
     }
     var p1 = studentFactory("ming", 20);
     var p2 = studentFactory("hong", 18);

Disadvantages: the factory pattern has its drawbacks, the biggest of which is the problem of object type recognition. We can only determine the Object type (p1 instanceof Object), but we cannot determine which type it is. Students created using the factory pattern all have similar properties and methods, but with different values. A better solution is to create a Student function so that all objects are of type Student. So the factory mode is not bad, but the constructor mode is better.

Constructor for custom type:

Constructors can be used to create specific types of objects.


     function Student(name,age) {
         this.name = name;
         this.age = age;
         this.sayName = function () {
             alert(this.name);
         }
     }
     var p3 = new Student("ming", 20);
     var p4 = new Student("hong", 18);
     alert(p3 instanceof Student);
    alert(p3.sayName==p4.sayName); //false

Cons: the downside of custom constructors is that each object recreates its own methods, which are the same (like sayName) but not the same (p3.sayname and p4.sayname are not equal).

Prototype mode:

Define an empty function, and then add all the properties and methods to the stereotype so that all objects share those properties and methods.


     function Student() {};
     Student.prototype.name = "ming";
     Student.prototype.age = 20;
     Student.prototype.friends = ['qi'];
     Student.prototype.sayName = function () {
         alert(this.name);
     };

Disadvantages: some attributes cannot be Shared, and sharing can bring problems back, for example: friends. Most friends of every student are different.

Combination of constructor and prototype:


     function Student(name, age, friends) {
         this.name = name;
         this.age = age;
         this.friends = friends;
     }
     Student.prototype = {
         constructor: Student,
         sayName: function () {
             alert(this.name);
         }
     };

Summary: the combination of constructors and stereotypes is a widely accepted way to create custom types. It is also the best of the above methods.

In fact, there are many methods to create objects above, but there may still be some special scenarios that need further optimization.

Dynamic prototype mode:

It is an optimization of the combination of constructor and prototype. For those common properties and methods, if initialized, do not have to initialize again, improve efficiency.


       function Student(name, age) {
           this.name = name;
           this.age = age;
           if ((typeof this.sayName) != "function") {
               Student.prototype.sayName = function () {
                   alert(this.name);
               }
           }
       }
       var stu = new Person("ming", 20);
       //alert(stu instanceof Student);
       stu.sayName();
      var stuNew = new Person("hong", 18);
      //alert(stuNew instanceof Student);
      stuNew.sayName();

The sayName method is initialized only once when multiple student objects are created.

Finally, there is a useful way to create an object, which is the secure constructor.

Secure constructor pattern:

This and new are disabled in this mode, and all objects have no public properties. The value of a variable can only be read, not modified.


      ////Secure constructor mode
      function Student(name, age) {
          var o = new Object();
          o.sayName = function () {
              alert(name);
          }
          return o;
      }
      var stu = Student("ming", 21);
      stu.sayName();

The above summarizes several common methods of Javascript to create custom objects, very comprehensive, if you have better, please contact me, this article is constantly updated.


Related articles: