Prototype attribute interpretation and common methods in JS

Source: Internet
Author: User

1, the definition of prototype

Each object in JavaScript has the prototype property, and the prototype property of the object in JavaScript is interpreted as a reference to the object type prototype.

Each constructor has a property called a prototype. This property is useful: Declare a common variable or function for a particular class.

You do not need to explicitly declare a prototype property because it exists in every constructor. You can look at the following example:

function Test () {}alert (test.prototype); Output "Object"

1.1. Prototype design mode

The main idea of the prototype method is that there are now 1 class A, and I want to create a class B, which is a prototype and can be extended. We call the prototype of B A.

1.2. JavaScript methods can be divided into three categories:

Class A methods

B Object method

C Prototyping Method

function people (name) {  this.name=name;  Object method This  . Introduce=function () {    alert ("My name is" +this.name);}  } Class Method People.run=function () {  alert ("I can Run");} Prototype Method People.prototype.introducechinese=function () {  alert ("My name is" +this.name);}//Test var p1=new people (" Windking ");p 1. Introduce (); People.run ();p 1. Introducechinese ();

1.3. Add attributes to Prototype

As you can see above, prototype is an object, so you have the ability to add properties to it. The property you add to prototype will be the common property of the object created using this constructor.

For example, I have a data type below fish, and I want all the fish to have these properties: livesin= "Water" and price=20; To achieve this, I can add those attributes to the prototype of the constructor fish.

function Fish (name, color) {   this.name=name;   This.color=color;} fish.prototype.livesin= "Water"; fish.prototype.price=20;
var fish1=new fish ("Mackarel", "Gray"), Var fish2=new fish ("Goldfish", "orange"), var fish3=new fish ("Salmon", "white"); for (int i=1; i<=3; i++) { alert (fish.name+ "," +fish.color+ "," +fish.livesin+ "," +fish.price ");}

The output should be:

"Mackarel, Gray, water," "Goldfish, orange, water," "Salmon, white water, 20"

You see all the fish have attributes livesin and price, we don't even specifically declare these attributes for each different fish. this is because when an object is created, the constructor assigns its property prototype to the internal property __proto__ of the new object. This __proto__ is used by this object to find its properties .

You can also add a common function to all objects by prototype. Here's a good thing: you don't need to create and initialize this function every time you construct an object. To explain this, let's take a look back at example DT9 and use prototype to rewrite it.

1.4. Adding functions to objects with prototype

function Employee (name, salary) {    this.name=name;                   This.salary=salary;} Employee.prototype.getsalary=function getsalaryfunction () {    return this.salary;} Employee.prototype.addsalary=function addsalaryfunction (addition) {    this.salary=this.salary+addition;} VAR boss1=new employee ("Joan", 200000), VAR boss2=new employee ("Kim", 100000), VAR boss3=new employee ("Sam", 150000);

The result of the output is:

Alert (Boss1.getsalary ());   Output 200000alert (Boss2.getsalary ());   Output 100000alert (Boss3.getsalary ());   Output 150000

How subclasses override the properties or methods of the parent class:

function AClass () {this    . property = 1;    This. Method = function () {        alert (1);    }} function AClass2 () {this   . Property2 = 2;   This. METHOD2 = function () {        alert (2);   }} Aclass2.prototype = new AClass (); AClass2.prototype.Property = 3; AClass2.prototype.Method = function () {   alert (4);} var obj = new AClass2 (); alert (obj. property), obj. Method ();

The output is:

3//4

You can add properties or methods on an object

function AClass () {this. property = 1;this. Method = function () {    alert (1);}} var obj = new AClass (); obj. Property2 = 2;obj. METHOD2 = function () {    alert (2);} Alert (obj. Property2); obj. METHOD2 ();

The output is:

2//2
The property or method of the custom type cannot be changed externally by prototype. As you can see, the properties and methods of the call are still the result of the original definition. That is, when the prototype method and the object method invoke the same properties and functions, the properties and functions inside the object's methods are executed.
function AClass () {this. property = 1;this. Method = function () {    alert (1);}} Aclass.prototype.Property = 2; Aclass.prototype.Method = function{    alert (2);} var obj = new AClass (); alert (obj. property), obj. Method ();

The output is:

1//1

1.5, A.prototype = new B ();

Understanding prototype should not confuse it with inheritance. A's prototype is an example of B, and it's understandable that a will clone the methods and properties in B all over again. A can use the methods and properties of B. The emphasis here is on cloning, not inheritance. This can happen: the prototype of A is an instance of B, and the prototype of B is also an instance of a.

Let's look at an example of an experiment:

function BaseClass () {  this.showmsg = function () {     alert ("Baseclass::showmsg");}     } function Extendclass () {}extendclass.prototype = new BaseClass (); var instance = new Extendclass (); instance.showmsg (); Show Baseclass::showmsg

We first defined the BaseClass class, and then we want to define extentclass, but we are going to use an instance of BaseClass as a prototype, to clone the Extendclass also contains showmsg this object method.

Extendclass.prototype = new BaseClass () can be read as: Extendclass was created as an instance of BaseClass as a prototype clone.

Then there is a question, what if the Extendclass itself contains a method with the same name as the BaseClass method?

Here is the extended Experiment 2:

function BaseClass () {    this.showmsg = function () {        alert ("Baseclass::showmsg");}       } function Extendclass () {    this.showmsg =function () {        alert ("Extendclass::showmsg");}    } Extendclass.prototype = new BaseClass (), var instance = new Extendclass (); instance.showmsg ();//Display extendclass::showmsg

Experimental results show that the function will go to the function of the main body to find, if found to run, can not find the prototype to find the function. Or it can be understood that prototype does not clone a function with the same name .

Then there will be a new question: What if I want to use an instance of Extendclass instance call BaseClass object method ShowMsg?

The answer is that you can use call:

Extendclass.prototype = new BaseClass (), var instance = new Extendclass (), var baseinstance = new BaseClass (); baseinstance. Showmsg.call (instance);//Display baseclass::showmsg

Here's Baseinstance.showMsg.call (instance); read as "invoke instance as Baseinstance, invoke its object method ShowMsg"

Well, someone here might ask, why not BaseClass.showMsg.call (instance);

This is the difference between the object method and the class method, and we want to invoke the BaseClass object method.

1.6. Important differences between object methods and object creation through new

The difference is that the function-defined method (the object method) has a prototype property, and the object generated with new does not have this prototype property. That is, the prototype property is the proprietary property of an object method or construction method. The prototype attribute also points to a prototype object, noting that the prototype property and the prototype object are two different things, be aware of the difference. There is another constructor property in the prototype object, and this constructor property also points to a constructor object, which is exactly the function itself. As shown below:

function person (name)  {     this.name=name;     This.showme=function ()          {             alert (this.name);          }  };    var one=new person (' JS ');    Alert (one.prototype)//undefined  alert (typeof person.prototype);//object  alert ( Person.prototype.constructor);//function person (name) {...};  

Finally, the following code, if understood clearly, is understood in this article:

 <script type= "Text/javascript" >function BaseClass () {this.showmsg = function () {alert ("BaseClass:       : ShowMsg ");    } this.baseshowmsg = function () {alert ("baseclass::baseshowmsg"); }}baseclass.showmsg = function () {alert ("baseclass::showmsg static");}    function Extendclass () {this.showmsg =function () {alert ("extendclass::showmsg"); }}extendclass.showmsg = function () {alert ("Extendclass::showmsg static")}extendclass.prototype = new BaseClass (); var i Nstance = new Extendclass (); instance.showmsg (); Display extendclass::showmsginstance.baseshowmsg (); Display baseclass::baseshowmsginstance.showmsg (); Display Extendclass::showmsgbaseclass.showmsg.call (instance);//display baseclass::showmsg Staticvar baseinstance = new BaseClass (); Baseinstance.showMsg.call (instance);//display baseclass::showmsg</script> 
Summary: In this article, the prototype attribute, which often appears in JavaScript and is difficult to understand, in meaning, uses the method (adds a property to the prototype, adds a function to the object with prototype), In the addition of functions and call content functions encountered in the process of some problems to provide a corresponding solution and other aspects of the relevant explanations, I hope that everyone has help, like, remember to move hands pointing point recommended Oh!

Prototype attribute interpretation and common methods in JS

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.