Examples of differences between using prototype and not using js class-defined functions

Source: Internet
Author: User

I have been using js to write self-built object-oriented methods. One problem is to define a method as follows:
Copy codeThe Code is as follows:
Function ListCommon2 (first, second, third)
{
This. First = function ()
{
Alert ("first do" + first );
}
}
ListCommon2.do1 = function (first)
{
// This. First ();
Alert ("first do" + first );
}
ListCommon2.prototype. do2 = function (first)
{
// This. First ();
Alert ("first do" + first );
}

What is the difference between the two methods? What is the function of using prototype?

Test code:
Copy codeThe Code is as follows:
Var t1 = new ListCommon2 ("boiling water 1", "Tea 1", "drinking 1 ");
// T1.do1 (); // call error
ListCommon2.do1 ("boiling water 1 ");
Var t2 = new ListCommon2 ("boiling water 2", "Tea 2", "drinking 2 ");
T2.do2 ("boiling water 2 ");//
// ListCommon2.do2 ("boiling water 1"); // call error

After testing, we found that the prototype method is not used as the static method of the class, so we can call ListCommon2.do1 ("boiling water 1");. If so, an error occurs, t1.do1 ();

On the contrary, the prototype method is equivalent to the instance method of the class, which can only be used after the new method is not allowed. ListCommon2.do2 ("boiling water 1"); in this case, an error occurs.

Conclusion: The method defined by prototype is equivalent to the instance method of the class and can only be used after it is new. The restrictions on the instance method of the class that can be called in functions are similar.

If you do not use a method defined by prototype, it is equivalent to a static method of the class. You can use it directly without the need for new methods. The restrictions on the static method of the class that can be called in functions are also similar.

For example, you cannot call this. First ();

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.