The usage of prototype in js is described in detail

  • 2020-03-29 23:43:46
  • OfStack

Prototype is a method for a class of objects introduced in IE 4 and later, and is especially handy because it is a way to add methods to class objects! This may sound a bit messy, but don't worry, I'll explain this particular method with an example:

First, let's take a look at the concept of classes. JavaScript itself is an object-oriented language, and the elements involved are all attached to a particular class depending on their attributes. We have common classes include: Array (Array), logic variables (Boolean), Date (Date), structure variables (Function), numerical variables (Number), Object (Object), String variable (String), etc., and related methods of a class, and programmers often use (in this case to the attention of the classes and properties to distinguish how method), such as an Array of push method, Date get series, String, the split method, etc.
But in the actual process of programming do you feel that the existing methods are inadequate? The prototype method! In the following, the specific use method of prototype will be explained by examples from the simple to the deep:

1. The simplest example, learn about prototype:

(1) Number. Add (num

Function (num){return(this+num); }
Test: alert((3). Add (15)) -> According to 18


(2) boolean.rev () : function, the Boolean variable is inverted

Boolean. Prototype.rev = function(){return(! This); }
Test: alert((true). Rev ()) -> According to false

Isn't it simple? This section only tells the reader about another method, and this is how it is used.

2. Implementation and enhancement of existing methods.

(1) Array. Push (new_element)
Effect: adds 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 it so that it can add more than one element 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;
     }

It's not hard to understand, is it? In the same way, you can consider how to remove any number of elements at any location by augmenting array.pop.

(2) the String length
Action: this is actually a property of the String class, but because JavaScript treats all corners and half corners as a single character, it may cause some problems in some practical applications. Now we use prototype to make up for this.
Implementation method:


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

Test: alert("EaseWe Spaces". CnLength ()) -> According to 16
Here are some regular expression methods and the encoding principle of full-angle characters, because it belongs to the other two large categories, this article does not explain, please refer to the relevant materials.

3. The implementation of new functions goes deep into prototype: in the actual programming, I will definitely use not only the enhancement of existing methods, but also more requirements of implemented functions. I will give two examples of solving practical problems with prototype:


  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 ("EaseWe Spaces". Left (8)) -> Displays the EaseWe space
        Alert ("EaseWe Spaces". Left (8,true)) -> EaseWe appear empty
This method USES the string.tlength () method mentioned above, and you can combine some nice new methods between custom methods.

(2) the Date. DayDiff ()
Function: calculate the interval between two date-type variables (year, month, day, week)
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 (2002, 1)))) - > According to 329
        Alert ((new Date ()). DayDiff ((new Date (2002, 1)), and "m")) - > According to 10
Of course, you can expand that even further to figure out the response time in hours, minutes, or even seconds.

(3) Number. The fact ()
Effect: factorial of a 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());
     }

Alert ((4). Fact ()) -> According to 24
This method mainly demonstrates that the recursive method is also feasible in the prototype method!



The object-oriented features that JavaScript can achieve are:
, public field
, public Method
, private field
, private field
, method overload
, constructor
・ events (event)
, single inherit
, subclasses override superclass properties or methods (override)
, static attribute or method (static member)


Example 1 (type of behavior allowed in JavaScript) : you can add behavior to a type using proptotype on the type. These behaviors can only be expressed on an instance of a type. The types allowed in JS are Array, Boolean, Date, Enumerator, Error, Function, Number, Object, RegExp, String


<script type="text/javascript">   
Object.prototype.Property = 1;   
Object.prototype.Method = function ()   
{   
    alert(1);   
}   

var obj = new Object();   
alert(obj.Property);   
obj.Method();   
</script>   

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

Example 2 (prototype limitation) : you cannot use prototype on an instance, otherwise a compilation error occurs

<script type="text/javascript">   
var obj = new Object();   
obj.prototype.Property = 1; //Error  
//Error  
obj.prototype.Method = function()   
{   
    alert(1);   
}   
</script>   

<script type="text/javascript">var obj = new Object();obj.prototype.Property = 1; //Error//Errorobj.prototype.Method = function(){ alert(1);}</script>

Example 3 (how to define static members on a type) : you can define "static" properties and methods for a type, simply by calling them directly on the type

<script type="text/javascript">   
Object.Property = 1;   
Object.Method = function()   
{   
    alert(1);   
}   

alert(Object.Property);   
Object.Method();   
</script>   

<script type="text/javascript">Object.Property = 1;Object.Method = function(){ alert(1);} alert(Object.Property);Object.Method();</script>

Example 5 () : this example demonstrates the common way to define a type in JavaScript

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

Example 6 (types of behavior allowed in JavaScript) : you can use prototype externally to add properties and methods to a custom type.

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

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

Example 8 () : properties can be changed on an object. You can also change methods on objects. (contrary to popular object-oriented concepts)

<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();   
</script>  
<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();</script>

Example 9 () : you can add properties or methods to an object

<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();   
</script>   

<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();</script>

Example 10 (how to have a type inherit from another type) : this example illustrates how a type can inherit from another type.

<script type="text/javascript">   
function AClass()   
{   
       this.Property = 1;   
       this.Method = function()   
       {   
              alert(1);   
       }   
}   

function AClass2()   
{   
       this.Property2 = 2;   
       this.Method2 = function()   
       {   
              alert(2);   
       }   
}   
AClass2.prototype = new AClass();   

var obj = new AClass2();   
alert(obj.Property);   
obj.Method();   
alert(obj.Property2);   
obj.Method2();   
</script>   

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

  Example 11 (how to redefine superclass members in a subclass) : this example shows how a subclass overrides a superclass property or method.

<script type="text/javascript">   
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();   
</script>   


Related articles: