Javascript prototype details

Source: Internet
Author: User

Javascript prototype details
1. Basic prototype features:
Ps: 1. A prototype and a class in other languages, defined attributes, and methods can be shared by all objects produced by this class.
2. Modifying the attributes or methods of the prototype takes effect immediately. The attributes and methods of its derived subclass also change.
Example 1:
Function Mytest (){
}
Mytest. prototype. name = "jerry ";
Var test1 = new Mytest ();
Alert (test1.name); // jerry
Mytest. prototype. name = "jack ";
Var test2 = new Mytest ();
Alert (test2.name); // jack
Alert (test1.name); // jack alert (Mytest. prototype. isPrototypeOf (test1 ));

2. Internal explanation of prototype creation ps: each time JavaScript declares a function, it will create a prototype attribute for it. prototype is an object without other conditions, the prototype of the function has a constructor attribute. The constructor contains a pointer to the function to which the prototype attribute belongs.
Example 2: function f (){
}
Alert (f. prototype); // object
Alert (f. prototype. constructor = f); // true 3. advantages and disadvantages of prototype writing ps: The biggest advantages and disadvantages of prototype are shared by others. sharing can reduce memory overhead, but it is easy to replace object attributes. in the first method, all objects generated by f have the name attribute, which increases the memory overhead. In the second method, the attributes are shared and only occupy one portion of memory, pay special attention to the assignment. There is no way to directly modify the attribute values in the prototype. Example 3: function f (){
This. name = "jack"
}


Function f (){}
F. prototype. name = "jack"
4. Several Methods for creating objects in a prototype
// 1 literal form
Function People (){}
People. prototype = {
Name: "jerry ",
Age: "22 ",
Sex: "male ",
Getname: function (){
Return this. name + "created successfully ...";
}
}
Var peo1 = new People ();
Alert (peo1.name); // jerry
Alert (peo1.getname (); // jerry created successfully
Alert (peo1.constructor = People); // false

// 2 create an object using the constructor
Function People (){
People. prototype. name = "jerry ";
People. prototype. age = "22 ";
People. prototype. getname = function (){
Return this. name + "created successfully ...";
}
}
Var peo1 = new People ();
Alert (peo1.name); // jerry
Alert (peo1.getname (); // jerry created successfully
Alert (peo1.constructor = People); // true


// Difference: the constructor attribute created by the independent variable does not point to the instance of the object, but to the object. The constructor points to the instance of the object.

// 3. Forcibly point to an object in the literal form
Function People (){}
People. prototype = {
Constructor: People,
Name: "jerry ",
Age: "22 ",
Sex: "male ",
Getname: function (){
Return this. name + "created successfully ...";
}
}
Var peo1 = new People ();
Alert (peo1.name); // jerry
Alert (peo1.getname (); // jerry created successfully
Alert (peo1.constructor = People); // true

// Disadvantage of the preceding object creation: the object value cannot be modified.

// 4. Composite constructor + prototype mode (the unchanged part uses the prototype mode and becomes something uses the constructor)
// Maintain independent Constructors
Function Animal (name, age ){
This. name = name;
This. age = age;
This. family = ['xiao Huang ', 'xiao Wang', 'xiao Wang '];

}
// Maintain the sharing prototype
Animal. prototype = {
Constructor: Animal,
Eat: function (){
Return (this. name + "eat .....");
}

}
Var dog = new Animal ('Dog', 2 );
Dog. family. push ('floret ');
Alert (dog. name); // dog
Alert (dog. family); // 'xiao Huang ', 'xiao Wang', 'xiao Wang ', 'xiao Hua'
Alert (dog. eat (); // dog eat...
Var pig = new Animal ('pig', 2 );
Alert (pig. name); // pig
Alert (pig. family); // 'xiao Huang ', 'xiao Wang', 'xiao Wang'
Alert (pig. eat (); // pig eat...

// 5 composite constructors. The prototype mode is encapsulated together: Dynamic Prototype
Function Animal (name, age ){
This. name = name;
This. age = age;
This. family = ['xiao Huang ', 'xiao Wang', 'xiao Wang '];
Alert ("prototype initialization starts ");
Animal. prototype. eat = function (){
Return (this. name + "eat .....");
}
Alert ("End of prototype initialization ");
}
// Prototype initialization starts, prototype initialization ends, prototype initialization starts, and prototype initialization ends
Var pig = new Animal ('pig', 2 );
Var cat = new Animal ('cat', 2 );

// Initialize the prototype only once. Modify the eat method.
// 6 composite constructors. The prototype mode is encapsulated together: Dynamic Prototype
Function Animal (name, age ){
This. name = name;
This. age = age;
This. family = ['xiao Huang ', 'xiao Wang', 'xiao Wang '];

If (typeof this. eat! = "Function "){
Alert ("prototype initialization starts ");
Animal. prototype. eat = function (){
Return (this. name + "eat .....");
}
Alert ("End of prototype initialization ");
}

}
// The prototype initialization starts and the prototype initialization ends,
Var pig = new Animal ('pig', 2 );
Var cat = new Animal ('cat', 2 );

5. using prototype to define your own method prototype is a method introduced in IE 4 and later versions for a certain type of objects, and its special convenience lies in: it is a method for adding methods to class objects! This may sound a little messy. Don't worry. I will explain this special method through the example below:

First, we need to first understand the concept of a class. JavaScript itself is an object-oriented language, and its elements depend on a specific class according to different attributes. Common classes include: Array, Boolean, Date, Function, and Number), Object, String, and other related class methods, it is also frequently used by programmers (here we need to distinguish between class attention and attribute sending methods), such as the push method of the array, the get method of the date series, and the split method of the string,

But in the actual programming process, I wonder if I feel the shortcomings of the existing method? The prototype method came into being! The following describes how to use prototype in a simple way:


1. The simplest example is prototype:
(1) Number. add (num): function, Number Addition
Implementation Method: Number. prototype. add = function (num) {return (this + num );}
Test: alert (3). add (15)-> show 18


(2) Boolean. rev (): returns the inverse of a Boolean variable.
Implementation Method: Boolean. prototype. rev = function () {return (! This );}
Test: alert (true). rev ()-> show false

Is it easy? This section only tells readers that this method is used in this way.


2. Implementation and enhancement of existing methods:
(1) Array. push (new_element)
Purpose: Add a new element to the end of the array.
Implementation Method:
Array. prototype. push = function (new_element ){
This [this. length] = new_element;
Return this. length;
}
Let's further enhance him so that he can add multiple elements at a time!
Implementation Method:
Array. prototype. pushPro = function (){
Var currentLength = this. length;
For (var I = 0; I <arguments. length; I ++ ){
This [currentLength + I] = arguments [I];
}
Return this. length;
}
Should it be difficult to understand? Similarly, you can consider how to delete any location and multiple elements by enhancing Array. pop (the specific code will not be detailed)

(2) String. length
Purpose: this is actually an attribute of the String class. However, JavaScript regards full and half-width as a character, which may cause some problems in some practical applications, now we use prototype to make up for this deficiency.
Implementation Method:
String. prototype. Tlength = function (){
Var arr = this. match (/[^ \ x00-\ xff]/ig );
Return this. length + (arr = null? 0: arr. length );
}
Test: alert ("aa la aa". Tlength ()-> show 8
Here we use some regular expression methods and full-byte character encoding principles. because they belong to the other two relatively large classes, this article does not describe them. Please refer to the relevant materials.


3. Implementation of new functions, in-depth prototype: in actual programming, it is certainly not only the enhancement of existing methods, but also more functional requirements, here are two examples of solving the actual problem using prototype:
(1) String. left ()
Problem: Anyone who has used vb should know the left function and take n characters from the left of the string. However, the full and half-width characters are considered as one character, this makes it impossible to intercept long strings in a mix of Chinese and English la S.
Purpose: truncates n characters from the left side of the string and supports full-width and half-width characters.
Implementation Method:
String. prototype. left = function (num, mode ){
If (! /\ D +/. test (num) return (this );
Var str = this. substr (0, num );
If (! Mode) return str;
Var n = str. Tlength ()-str. length;
Num = num-parseInt (n/2 );
Return this. substr (0, num );
}
Test: alert ("aa la aa". left (4)-> display aa la
Alert ("aa la aa". left (4, true)-> display aa
This method uses the String. Tlength () method mentioned above, and some good new methods can be combined between custom methods!

(2) Date. DayDiff ()
Function: Calculate the interval (year, month, day, week) between two date variables)
Implementation Method:
Date. prototype. DayDiff = function (cDate, mode ){
Try {
CDate. getYear ();
} Catch (e ){
Return (0 );
}
Var base = 60*60*24*1000;
Var result = Math. abs (this-cDate );
Switch (mode ){
Case "y ":
Result/= base * 365;
Break;
Case "m ":
Result/= base * 365/12;
Break;
Case "w ":
Result/= base * 7;
Break;
Default:
Result/= base;
Break;
}
Return (Math. floor (result ));
}
Test: alert (new Date (). DayDiff (new Date (329, 1)-> show
Alert (new Date (). DayDiff (new Date (, 1), "m")-> show 10
Of course, it can be further expanded to get the response hour, minute, or even second.

(3) Number. fact ()
Role: factorial of a certain number
Implementation Method:
Number. prototype. fact = function (){
Var num = Math. floor (this );
If (num <0) return NaN;
If (num = 0 | num = 1)
Return 1;
Else
Return (num * (num-1). fact ());
}
Test: alert (4). fact ()-> 24
This method mainly demonstrates that the recursive method is also feasible in the prototype method!

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.