Often interviewing on the front end or communicating with other peers is that when it comes to constructing a constructor in JS, it is best to use prototypes: define the method on the prototype of the constructor. The advantage is that the methods that are generated by the constructor all point to the index of a function, which can save memory.
Of course, there is no problem with this statement. It is just that in terms of implementation, it is not only possible to achieve such an effect 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. In this way, the generated instance methods also point to a function through the index, as follows:
// No prototype definition method is used: (function() { function Constractor() { this.method1 = method1; this.method2 = method2; } function method1() { } function method2() { }})();Generally, 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() { };})();There is nothing profound about the theory and implementation. It is just that in order to achieve the same purpose, different ways can be used. However, this method does not work when using the instanceOf operator to judge the inheritance relationship.
The detailed explanation of the benefits of using prototypes in js is the full content shared by the editor. I hope it can give you a reference and I hope you can support Wulin.com more.