Details about the benefits of using prototype to define methods in js, jsprototype
Often in front-end interviews or communicating with other colleagues, when talking about constructing constructors in JS, it is best to use a prototype: Define methods to the prototype of the constructor, the advantage is that all the methods of instances generated by the constructor point to the index of a function, which can save memory.
Of course, there is no problem with this statement. It is only in implementation that prototype is not used to achieve this effect. We can define methods in the form of functions outside the constructor, then use this. method = method. In this way, the generated instance method also points to a function through the index, as shown below:
// Do not use the prototype definition method (function () {function Constractor () {this. method1 = method1; this. method2 = method2;} function method1 () {} function method2 (){}})();
The prototype is generally used to define the time code as follows:
(Function () {function Constractor () {} Constactor. prototype = {method1: function () {}, method2: function () {}}; // or Constactor. prototype. method1 = function () {}; Constactor. prototype. method2 = function (){};})();
There is no profound theory or implementation, just to achieve the same purpose, we can use different ways, but this method does not work when the instanceOf operator is used to determine the inheritance relationship.
The benefits of using prototype in the above js definition method are all the content that I have shared with you. I hope you can give us a reference and support for more.