A brief analysis of how prototype defines itself

  • 2020-03-29 23:44:34
  • 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.Tlength = function(){
        var arr=this.match(/[^x00-xff]/ig);
        return this.length+(arr==null?0:arr.length);
    }

Test: alert("aa la la aa".Tlength()) -> According to eight

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. Implementation of new functions, in-depth study on prototype: In the actual programming, we need to use not only the enhancement of existing methods, but also the requirements of implementing functions. Here are two examples of using prototype to solve practical problems:

(1) the String. The left ()
Problem: the use of vb should know the left function, from the left of the string to take n characters, but the shortage is the full Angle, half Angle as a character, resulting in the mixed layout in Chinese and English cannot intercept the same length of the string

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 la aa". Left (4)) -> Show aa la la
          Alert ("aa la la aa". Left (4,true)) -> According to aa!

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!


Related articles: