Detailed explanation of the benefits of using the prototype of prototype definition method in js

  • 2021-07-01 06:26:17
  • OfStack

Often interviewing at the front end or communicating with other peers, when it comes to constructing the method of defining constructors in JS, it is best to use prototypes: defining methods on prototype of constructors. This has the advantage that all the methods generated by this constructor have indexes pointing to one function, which can save memory.

Of course, there is nothing wrong with this statement, but in terms of implementation, this effect can not be achieved only by using prototype. We can define the method outside the constructor in the form of a function, and then use this. method = method in the constructor, so that the methods of the generated instances also point to one function through indexes, as follows:


//  Do not use prototype definition methods: 
(function() {
  function Constractor() {
    this.method1 = method1;
    this.method2 = method2;
  }

  function method1() {
  }

  function method2() {
  }
})();

1. When using prototype definition, the code is as follows:


(function () {
  function Constractor() {
  }

  Constactor.prototype = {
    method1: function() {
    },
    method2: function() {
    }
  };
  
  //  Or 
  Constactor.prototype.method1 = function() {
  };
  Constactor.prototype.method2 = function() {
  };

})();

Neither the theory nor the implementation is profound, but there are different ways to achieve the same goal, but this way does not work when using instanceOf operator to judge inheritance relationship.


Related articles: