JavaScript must know the prototype

Source: Internet
Author: User

All content of this blog is used by Creative Commons Licenses license. When quoting this content, please retain W, source, and non-commercial .

Click RSS to subscribe. (Google Reader is recommended, if your browser does not support direct subscription, please add it directly in Google Reader.)

Summary

This series of blogs focuses on some of the advanced applications that are often confusing in javascript usage, including: prototype, closure, scope, this keyword. For a programmer who needs to improve his or her JavaScript level, these must be mastered.

This section mainly introduces prototype.

Contents

    • Summary
    • Onwards
    • Prototype
    • Conclusion
    • Resources
    • The RST source code of this article
Prototype

JavaScript is a prototype based programming language, and it is very different from our usual class based programming, and I enumerate the important points as follows:

    1. The function is first class object, which means that the function has the same language status as the object
    2. No classes, only objects
    3. Functions are also an object, so-called function objects
    4. Objects are passed by reference .

So this prototype based programming language how to achieve inheritance (oo one of the basic elements), this is the origin of prototype .

Look at the following code snippet:

function foo (A, B, c) {return a*b*c;} Alert (foo.length), alert (typeof foo.constructor), alert (typeof Foo.call); alert (typeof foo.apply); alert (typeof Foo.prototype);

For the above code, after running in the browser you will find:

    1. Length: Provides the number of arguments for a function
    2. Prototype: is an object
    3. All three of them are function.

and for any declaration of a function, it will have the 5 properties (methods or properties) described above.

Below we mainly look at the prototype.

Prototypefunction person (name, gender) {this.name = Name;this.gender = Gender;this.whoareyou = function () {// This is also called closure, where the intrinsic function can access the variables of the external function var res = "I ' m" + this.name + "and I ' m a" + This.gender + "."; return res;};} Then the object created by person has the following properties Person.prototype.age = 24; Person.prototype.getAge = function () {return this.age;}; Flag = TRUE;IF (flag) {var fun = new Person ("Tower", "male"), alert (fun.name), alert (Fun.gender), alert (fun.whoareyou ()); Alert (Fun.getage ());} Person.prototype.salary = 10000; Person.prototype.getSalary = function () {return this.name + "can earn about" + This.salary + "$ each month.";};/ /Below is the most magical place, we change the person's prototype, and this change is after creating fun//And this change makes fun also has the same properties and methods//inherited means that this if (flag) {Alert (Fun.getsalary ( ); alert (fun.constructor.prototype.age);//And this corresponds to your direct call to Person.prototype.agealert (Person.prototype.age);}

From the example above we can see that for prototype methods or properties, we can dynamically increase, and the object created by it automatically inherits the related methods and properties.

In addition, each object has a constructor property that points to the function object that created it, as fun.constructor in the previous example points to person.

Then a question arises naturally, what is the difference between the methods and properties declared in the function object and the objects declared by the prototype?

There are several differences:

    1. The methods and properties of self-declared are static , that is, after you declare, try to add new methods or modify existing methods, and do not affect the objects created by them, that is, inheritance fails
    2. And prototype can dynamically add new methods or modify existing methods, which is dynamic , once the parent function Object declares the associated prototype property, the object created by it automatically inherits The properties of these prototype.

Continue with the above example:

The flag = true;//function internally declares that the method is static and cannot be passed Person.school = "Iscas"; Person.whoareyou = function () {return "Zhutao";};/ /dynamically changing the method of the declaration period does not affect the method of the object created by it, that is, the so-called static if (flag) {alert (Person.school); alert (fun.school);//The output is "undefined" alert ( Person.whoareyou ()); Output Zhutaoalert (fun.whoareyou ()); I ' M Tower and I ' m a male.} Person.prototype.getSalary = function () {return "I can earn 1000000 USD";}; if (flag) {alert (fun.getsalary ());//has inherited the change, that is, the so-called dynamic}

Since there are properties of the function object itself and also the properties of the prototype, how is the object created by it to search for the corresponding property?

The basic is to follow the following process and sequence.

    1. First go to the properties of the function object itself, if found to execute immediately
    2. If 1 is not found, it will search for the prototype property, there are 2 results, find the direct execution, or continue to search the parent object 's parent prototype, until found, or reached prototype chain End (end of object)

It also answers that if the properties of the function object itself are resolved in the same way as the prototype property (duplicate name), the object of the function itself takes precedence .

Take another look at a multi-prototype chain example:

Example of a multiple prototype chain function Employee (name) {this.name = ""; this.dept = "General"; This.gender = "Unknown";} function WorkerBee () {this.projects = [];this.hascar = false;} Workerbee.prototype = new Employee; The first layer prototype chain function Engineer () {this.dept = "Engineer";//Overrides "Parent object" This.language = "JavaScript";} Engineer.prototype = new WorkerBee; Second layer prototype chain var Jay = new Engineer ("Jay"), if (flag) {alert (jay.dept);    Engineer, found the property of his own alert (Jay.hascar);  False, the search is the property of the previous layer of alert (jay.gender);  Unknown, the search is on the two-layer property}

The object relationship of the above example is as follows:

Conclusion

The prototype of JavaScript adds a lot of flexibility to the language itself, but the whole logic of thinking is different from class based programming, so it needs to be thought and figured out more.

And JavaScript is a functional language in the C language of the understanding of nature also need to think more.

In the next section I will continue to discuss another important and more easily mistaken knowledge closureof JavaScript.

Welcome to leave a message to discuss.

Resources
    1. Json
    2. Class based programming
    3. Prototype based programming
    4. Using Prototype Property in JavaScript

JavaScript must know the prototype

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.