JavaScript Learning Notes 6 prototype the basics

Source: Internet
Author: User
First we go on to the code above, and we'll extend this code:
Copy Code code as follows:

<script type= "Text/javascript" >
var person = function (name, age) {
THIS.name = name;
This.age = age;
This. introduce = function () {
Alert ("My name is" + THIS.name +). I ' m ' + this.age);
};
};
var person1 = new Person ("sarin", 21);
var person2 = new Person ("Kym", 26);
Alert (Person1. introduce = = Person2. introduce);
</script>


The result popped false. In other words, the methods of the two objects are different methods. So we know that in C #, each object maintains a method table, but the method table should point to the same address. If so, when we declare 100 objects, is not to create 100 copies of objects, is not a big waste of space?

So we think of this solution, with prototype:
Copy Code code as follows:

<script type= "Text/javascript" >
var person = function (name, age) {
THIS.name = name;
This.age = age;
};
Person.prototype.Introduce = function () {
Alert ("My name is" + THIS.name +). I ' m ' + this.age);
}
var person1 = new Person ("sarin", 21);
var person2 = new Person ("Kym", 26);
Alert (Person1. introduce = = Person2. introduce);
</script>


That's it. So are you going to say whether it's the same with prototype? In fact, I used to understand this, in this accidental experiment to see the problem.

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.