Details about the benefits of using prototype to define methods in js, jsprototype

Source: Internet
Author: User
Tags prototype definition

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.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.