SoFunction
Updated on 2025-03-01

Comparison of advantages and disadvantages of several ways to create objects by js

Comparison of several ways to create objects in js

1. Factory model

function createObj(name, sex){
    var obj = new Object();
     = name;
     = sex;
     = function(){
      alert();
    }
    return obj;
  }

var person = createObj('Tom', 'man');

Disadvantages: ① The type of the object cannot be determined (because they are all Objects).

②There is no association between multiple objects created.

2. Constructor

function createObj(name, sex){
     = name;
     = sex;
     = function(){
      alert();
    }
  }

  var person = new createObj('Tom', 'man');

Disadvantages: ① Repeated creation methods for multiple instances, and cannot be shared.

② Multiple instances have a sayName method, but none of them are instances of the same Function.

3. Prototype method

function createObj(){}

   = 'Tom';
   = 'man';
   = function(){
    alert();
  }

var person = new createObj();

Disadvantages: ① The parameters cannot be passed in, and the attribute value cannot be initialized.

②If the value of one of the instances is changed when the value of the reference type is included, it will be reflected in all instances.

4. Combination (constructor + prototype method) is recommended

function createObj(name, sex){
   = name;
   = sex;
 }
  = function(){
  alert();
 }

 var person = new createObj('Tom', 'man');

Advantages: The constructor shares instance properties, prototype sharing methods, and properties you want to share. Parameters can be passed and attribute values ​​can be initialized.

5. Dynamic prototype method

function createObj(name, sex){
   = name;
   = sex;
  if(typeof  != 'function'){
    = function(){
    alert();
   }
  }
 }

 var person = new createObj('Tom', 'man');

Note: If statement will only be called once, which means it will be executed when the first instance calls the method. All instances will then share the method. Under the dynamic prototype method, the prototype cannot be rewrited using object literals.

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.