JavaScript Creation Object prototype mode (iii)

Source: Internet
Author: User
Tags object constructor

First code:

function Human () {}
Human.prototype.name = "Genghis Khan";
Human.prototype.sex = "male";
Human.prototype.say = function () {
alert (this.name);
var man = new Human ();
Man.say ();        Genghis Khan
var woman = new Human ();
Woman.say (); Genghis Khan
alert (Man.say = = Woman.say);//true

Prototype is one of the very core points of knowledge in JavaScript. He is an important part of the object-oriented thinking in JavaScript.

Let's see where prototype is, with so much power.

Each function in JS has a prototype attribute, which we call a prototype. (This explanation is a bit rotten, equal to not say, no way, do not know how to give him the definition of ^_^);

One of the benefits of using a prototype object is to have all instances share the same properties and methods on the prototype.

In the example above, Name,sex,say are all located on prototype, so man and woman share these properties and methods. Although there are 2 instances in memory, they have only one copy of name and sex and say.

This is a great memory saver in a complex project.

Also because of this, the prototype model is better than the constructor pattern described in the previous section.

This simple prototyping model shows a lot of unrealistic things at one glance:

1. Since all the properties and methods are shared, is it enough that I instantiate an object?

2. Each object is an individual (has its own specific attributes or methods), but also has similarities (common attributes and methods),

Then there is the result of the interaction between the constructor pattern and the prototype pattern. This combination pattern continues in the next chapter.



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.