JavaScript Write class way of two _js object-oriented

Source: Internet
Author: User
2. Prototype mode
Copy Code code as follows:

/**
* Person class: Defines a human, has a property name, and a GetName method
*/
function person () {}
Person.prototype.name = "Jack";
Person.prototype.getName = function () {return this.name;}

The properties (fields) of the class are hung on the prototype.

Build several objects under test:
Copy Code code as follows:

var p1 = new Person ();
var p2 = new Person ();
Console.log (P1.getname ());//jack
Console.log (P2.getname ());//jack

It can be seen that the output is jack, so the disadvantage of the prototype method is not to construct the object instance through the parameters (generally each object's properties are not the same), the advantage is that all object instances share the GetName method (relative to the constructor method), does not cause memory waste.

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.