Home > Web Front-end > JS Tutorial > Detailed introduction to prototype usage in js_javascript skills

Detailed introduction to prototype usage in js_javascript skills

WBOY
Release: 2016-05-16 17:15:14
Original
1601 people have browsed it

Prototype is a method introduced in IE 4 and later versions for objects of a certain class, and the special thing is: it is a method for adding methods to objects of a class! This may sound a bit confusing, don’t worry, I will explain this special method through examples below:

First of all, we need to understand the concept of classes. JavaScript itself is an object-oriented language, and the elements involved are attached to a specific class based on their attributes. Our common classes include: array variables (Array), logical variables (Boolean), date variables (Date), structure variables (Function), numerical variables (Number), object variables (Object), string variables (String), etc. , and related class methods are also often 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 series method of the date, the split method of the string, etc.,
But in the actual programming process, do you feel the shortcomings of the existing methods? The prototype method came into being! Below, we will explain the specific use of prototype from shallow to deep through examples:

1. The simplest example, understand prototype:

(1) Number.add(num): Function, add numbers

Implementation method: Number.prototype.add = function(num){return(this num);}
Test: alert((3).add(15)) -> Display 18


(2) Boolean.rev(): Function, negate the Boolean variable

Implementation method: Boolean.prototype.rev = function(){return(!this);}
Test: alert((true).rev()) -> Display false

Isn’t it very simple? This section just tells readers about another method and how this method is used.

2. Implementation and enhancement of existing methods, first introduction to prototype:

(1) Array.push(new_element)
Function: Add a new element to the end of the array
Implementation method:

Copy code The code is as follows:

 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 once!
Implementation method:

Copy code The code is as follows:

 Array.prototype.pushPro = function() {
var currentLength = this.length;
for (var i = 0; i < arguments.length; i ) {
this[currentLength i] = arguments[i];
}
return this.length;
}

It shouldn’t be difficult to understand, right? By analogy, you can consider how to delete any number of elements at any position by enhancing Array.pop (the specific code will not be detailed)

(2) String.length
Function: This is actually an attribute of the String class, but since JavaScript treats both full-width and half-width as one character, it may cause certain problems in some practical applications. Now we use prototype to make up for this shortcoming.
Implementation method:

Copy code The code is as follows:

String.prototype.cnLength = function(){
var arr=this.match(/[^x00-xff]/ig);
return this.length (arr==null?0:arr.length);
}

Test: alert("EaseWe Spaces".cnLength()) -> Display 16
Some regular expression methods and full-width character encoding principles are used here, because they belong to two other larger categories , this article does not include any explanation, please refer to relevant materials.

3. To implement new functions, go deep into prototypes: What is used in actual programming is definitely not only the enhancement of existing methods, but also more functional requirements. Below I will give two examples of using prototypes to solve practical problems. Example:

(1) String.left()
Problem: Anyone who has used VB should know the left function, which takes n characters from the left side of the string. However, the disadvantage is that both full-width and half-width are regarded as one character, causing Equal-length strings cannot be intercepted in a mixed layout of Chinese and English
Function: intercept n characters from the left side of the string, and support the distinction between full-width and half-width characters
Implementation method:

Copy code The code is as follows:

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);
}

Experiment:
alert("EaseWe Spaces".left(8)) -> Display EaseWe space
alert("EaseWe Spaces".left(8,true)) -> Display EaseWe Empty
This method uses the String.Tlength() method mentioned above, and some good new methods can also be combined between custom methods!

(2) Date.DayDiff()
Function: Calculate the interval between two date variables (year, month, day, week)
Implementation method:

Copy code The code is as follows:

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; 🎜>
Test: alert((new Date()).DayDiff((new Date(2002,0,1)))) -> Display 329
alert((new Date()).DayDiff((new Date(2002,0,1)),"m")) -> Display 10
Of course, it can also be further expanded to get the response hours, minutes, or even seconds.
(3) Number.fact() Function: Factorial of a certain number

Implementation method:



Copy code

The code is as follows:

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()) -> Display 24
This method mainly shows that the recursive method is also feasible in the prototype method!



The object-oriented features that JavaScript can implement are:
·Public field
·Public Method
·Private field
·private field
·method overload
·constructor
·event
·single inherit
·Subclass overrides the attributes or methods of the parent class (override)
·Static attributes or methods (static member)


Example 1 (Types that allow adding behaviors in JavaScript): You can use proptotype on types to add behaviors to the type. These behaviors can only be manifested on instances of the type. The types allowed in JS are Array, Boolean, Date, Enumerator, Error, Function, Number, Object, RegExp, String

Copy code The code is as follows:





Example 2 (Restrictions on the use of prototype): You cannot use prototype on the instance, otherwise a compilation error will occur
Copy the code The code is as follows:





Example 3 (How to define static members on a type): You can define "static" properties and methods for the type and call them directly on the type
Copy code The code is as follows:



Example 5 (): This example demonstrates the usual method of defining a type in JavaScript
Copy code The code is as follows:




Example 6 (Types that allow adding behaviors in JavaScript): You can use the prototype externally as Custom types add properties and methods.
Copy code The code is as follows:





Example 8 (): Properties can be changed on the object. (This is for sure) You can also change methods on the object. (Different from the general object-oriented concept)
Copy code The code is as follows:

< script type="text/javascript">
function Aclass()
{
this.Property = 1;
this.Method = function()
{
alert(1 );
}
}
var obj = new Aclass();
obj.Property = 2;
obj.Method = function()
{
alert(2 );
}
alert(obj.Property);
obj.Method();



Example 9 (): You can add properties or methods to the object
Copy code The code is as follows:





Example 10 (How to make one type inherit from another type): This example illustrates how one type inherits from another type.
Copy code The code is as follows:

  



 例子十一(如何在子类中重新定义父类的成员):这个例子说明了子类如何重写父类的属性或方法。
复制代码 代码如下:

  
Related labels:
js
source:php.cn
Previous article:Text fade-in and fade-out effect based on jquery_jquery Next article:Two ways to cancel verification of Js in MyEclipse_javascript skills
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Latest Issues
Related Topics
More>
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template