Learn more about prototyping Prototype_ basics in JavaScript

Source: Internet
Author: User

JavaScript is a prototype based programming language, which differs greatly from our usual class based programming, and I enumerate the important points as follows:

1. The function is a class object, which means that the function has the same language status as the object.
2. No class, only objects
3. Function is also an object, the so-called function object
4. Objects are passed by reference
So how does this prototype based programming language achieve inheritance (an essential element of OO), which is the origin of prototype.

Look at the following code fragment:

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, run with a browser and you will find that:

1.length: Provides the number of parameters of a function
2.prototype: Is an object
3. The other three are function
For any declaration of a function, it will have the 5 property (method or attribute) described above.

Below we mainly look down prototype.

//prototype function person (name, gender) {this.name = name; this.gender = gender; 
Whoareyou = function () {//This is also called closure, the internal 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 attributes 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.G
Etage ());
} Person.prototype.salary = 10000;
Person.prototype.getSalary = function () {return this.name + ' can earn about ' + this.salary + ' RMB each month. '}; Here is the Magic place where we change the person's prototype, and this change is after the creation of fun//And this change makes fun also have the same attributes and methods//inheritance meaning that this if (flag) {alert (fun.getsalary
());
alert (fun.constructor.prototype.age);//And this is the equivalent of calling Person.prototype.age alert (Person.prototype.age) directly; }

From the example above we can see that we can dynamically increase the prototype method or attribute, and the objects created by it automatically inherit the related methods and properties.

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

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

There are several differences:

1. The methods and properties declared by themselves are static, which means that after you declare them, you try to add new methods or modify existing methods without affecting the objects created by them or inheriting the failure
2. Prototype can dynamically add new methods or modify existing methods, which is dynamic, and once the parent function object declares the associated prototype property, the objects created by it automatically inherit the properties of these prototype.
Continue with the above example:

Flag = true;
The method of internal declaration of function is static, the
Person.school = "Iscas" that cannot be passed;
Person.whoareyou = function () {return
"Zhutao";
};/ /The method of dynamically changing 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);//output is "undefined"
alert (Person.whoareyou ());//Output Zhutao
alert (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 there are prototype properties, then how does the object created by it search for the corresponding property?

Basically follow the following process and sequence.

1. Search the properties of the function object itself, if you find an immediate execution
2. If 1 is not found, will go to search for the prototype property, there are 2 kinds of results, find the direct execution, otherwise continue to search the parent object's prototype, until found, or reached the end of prototype chain (the end will be object)
It also answers if the function object itself has the same property as the prototype property (duplicate name), the object of the function itself takes precedence.

Typical examples of prototype

Friends who have used jQuery or Prototype libraries will probably know that the trim method is usually available in these libraries.

Example:

String.prototype.trim = function () {return
 this.replace (/^\s+|\s+$/g, ');


Trim Usage:

' foo bar '. Trim (); ' Foo Bar '

But there is a drawback, because the JavaScript engine in the newer version of the browser provides the Trim method itself in the String object, so our own definition of trim will overwrite its own trim. In fact, before we define the trim method, we can do a simple test to see if we need to add this method ourselves:

if (! String.prototype.trim) {
 String.prototype.trim = function () {return
 this.replace (/^\s+|\s+$/g, ');}


Prototype chain

When any object is defined or instantiated in JavaScript, it is appended with a hidden attribute called __proto__, which is what the prototype chain relies on to form. But never access the __proto__ property directly, because some browsers do not support direct access to it. In addition, __proto__ and object prototype properties are not the same thing, they each have their own purposes.

How do you understand it? In fact, when we create the MyObject function, we actually create an object of the function type:

Console.log (typeof MyObject); function

To illustrate, a Function is a predefined object in JavaScript, so it also has its own predefined attributes (such as length and arguments) and methods (such as call and apply) and, of course, __proto__, to implement the prototype chain. That is, there may be snippets of code similar to the following in the JavaScript engine:

Function.prototype = {
 arguments:null,
 length:0,
 call:function () {
 //Secret Code
 },
 Apply:function () {
 //Secret Code
 },
 ...
};

In fact, JavaScript engine code is not as simple as this, just a description of how the prototype chain works.

We defined a function myObject, which also has a parameter name, but does not give it any other attributes, such as length or other methods, such as call. So why does the following code work?

Console.log (myobject.length); Result: 1, is the number of parameters

This is because when we define myObject, we also define a __proto__ attribute and assign it to Function.prototype (refer to the previous code fragment), so we can access it like any other property. Myobject.length, even if we do not define this attribute, because it will follow the __PROTO__ prototype chain up to find length, eventually found in the Function inside.

So why is the value of the length attribute found to be 1 instead of 0, and when is it to be assigned a value? Because MyObject is an instance of a Function:

Console.log (MyObject instanceof Function); True
console.log (myObject = = Function);//False

When an object is instantiated, the __proto__ property of the object is assigned to the stereotype object of its constructor, in this case the Function, in which the constructor goes back to calculate the number of parameters and change the value of length.

Console.log (myobject.__proto__ = = = Function.prototype); True

And when we create a new instance with the newer keyword, the __proto__ of the new object will be assigned to Myobject.prototype because the current constructor is myObject, not a function.

var myinstance = new MyObject (' foo ');
Console.log (myinstance.__proto__ = = = Myobject.prototype); True

In addition to access to call and apply inherited from Function.prototype, the new object also accesses the GetName method inherited from MyObject:

Console.log (Myinstance.getname ()); Foo
 
var mysecondinstance = new MyObject (' Bar ');
 
Console.log (Mysecondinstance.getname ()); Bar
Console.log (Myinstance.getname ());//foo

In fact, this is equivalent to the prototype object as a blueprint, and then can be based on this blueprint to create N new objects.

Look at one more example of a multiple prototype chain:

Multiple prototype chain example
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";//overwrite "Parent object"
this.language = " JavaScript ";
}
Engineer.prototype = new WorkerBee; Second layer prototype chain
var jay = new Engineer ("Jay");
if (flag)
{
alert (jay.dept);//engineer, find its own property
alert (Jay.hascar);//False, search for properties
of the previous level alert (Jay.gender); Unknown, the search is on the two-level properties of their own
}

The object relationships for the above example are as follows:

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.