SoFunction
Updated on 2025-02-28

Property description of JavaScript prototype object

When referring to a function or property of an object through point notation, if there is no function or property on the object, the object's prototype property will be used. When this happens, the object referenced by the object's prototype property is checked to see if there is a requested property or function. If the object referenced by the prototype attribute also does not have the required functions or attributes, the prototype attribute of this object (the object referenced by the prototype attribute) will be further checked, and searched up along the chain in turn until the requested function or attribute is found, or the chain end is reached. If the chain end has not been found yet, undefined is returned. In this sense, this inheritance structure should be more of a "has a" relationship, rather than a "is a" relationship
God,I understand nothing,what to do? It seems that I am very awesome, but to be honest, I can't understand it either! ^_^ ^_^ ^_^
2. Prototype attribute application example
The common classes we are: array variables (Array), logical variables (Boolean), date variables (Date), structural variables (Function), numerical variables (Number), object variables (Object), string variables (String), etc. The methods of related class are also commonly used by programmers (here we need to distinguish the attention of the class and the attribute sending method), 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, I wonder if I feel the shortcomings of the existing methods? The prototype method came into being! Below, we will explain the specific usage method of prototype from shallow to deep through examples:
Let’s take a look at a very stupid example:

JavaScript Code
function func(){   
    = “prototype of func”;   
}   
var f = new func();          
alert();  //prototype of func
First create a func object, set the name attribute of the func object, and instantiate f;

1. A few simple examples:
(1) Add up the numbers:
JavaScript Code
=function(num){   
return (this+num);//This here points to Number
};   
alert((3).add(15));//18  
(2) (): Function, Boolean variable inverse
Implementation method: = function(){return(!this);}
Test: alert((true).rev()) -> Show false
2. Implementation and enhancement of existing methods, and first understand prototype:
(1) (new_element)
Function: Add a new element at the end of the array
Implementation method:
= function(new_element){
        this[]=new_element;
        return ;
    }
Let's further enhance him so that he can add multiple elements at once!
Implementation method:
= function() {
        var currentLength = ;
        for (var i = 0; i < ; i++) {
            this[currentLength + i] = arguments[i];
        }
        return ;
    }
It shouldn't be difficult to understand, right? And so on, you can consider how to delete any location and any multiple elements through enhancement (I won’t go into details about the specific code)

3. Implementing new functions, in-depth prototype: What is used in actual programming is definitely not just to enhance existing methods, but also to implement more functional requirements. Let me give you two examples of using prototype to solve practical problems:
(1) ()
Problem: Those who have used vb should know the left function, which takes n characters from the left side of the string, but the disadvantage is that the full and half-width are regarded as one character, which makes it impossible to intercept strings of equal length in the mixed layout of Chinese and English.
Function: Seize n characters from the left side of the string and support the distinction between full-width and half-width characters.
Implementation method:
= function(num,mode){
        if(!/\d+/.test(num))return(this);
        var str = (0,num);
        if(!mode) return str;
        var n = () – ;
        num = num – parseInt(n/2);
        return (0,num);
    }
Test: alert("aalaaaa".left(4)) -> Show aalala
alert("aalaaaa".left(4,true)) -> Show aa
This method uses the () method mentioned above, and some good new methods can be combined between custom methods!
(2) ()
Function: Calculate the interval time between two date variables (year, month, day, week)
Implementation method:
= function(cDate,mode){
        try{
            ();
        }catch(e){
            return(0);
        }
        var base =60*60*24*1000;
        var result = (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((result));
    }
Test: alert((new Date()).DayDiff((new Date(2002,0,1)))) -> Display 329
alert((new Date()).DayDiff((new Date(2002,0,1)),"m")) -> Show 10
Of course, it can also be further expanded to obtain the hours, minutes, or even seconds of the response.
(3) ()
Function: the factorial of a certain number
Implementation method:
=function(){
        var num = (this);
        if(num<0)return NaN;
        if(num==0 || num==1)
            return 1;
        else
            return (num*(num-1).fact());
    }
Test: alert((4).fact()) -> Show 24
This method mainly shows that the recursive method is also feasible in the prototype method!
Example:
Take the maximum value of the array:
JavaScript Code
var oArr=new Array();   
oArr=[100,190,199,189,3000,400,4001];   
=function(){   
    var i,max=this[0];   
    for(i=1;i<;i++){   
        if(max<this[i]){   
            max=this[i];   
        }   
    }   
    return max;   
}   
alert(());  
The instance adds methods to user-defined classes:
JavaScript Code
function TestObject()   
 {   
     this.m_Name = “ffffffffff”;   
 }   

  = function()   
 {   
     alert(this.m_Name);   
 };   
var f=new TestObject();   
();  
Update the prototype of the custom class:

JavaScript Code
function TestObjectA()   
{   
   = function()   
   {   
      alert(‘()');   
   }   
}   

function TestObjectB()   
{   
   = function()   
   {   
      alert(‘()');   
   }   
}   

= new TestObjectA();  
I heard that this is a wrong inheritance; I learned it slowly in the future.
Looking at another example, you and I are probably going crazy:

JavaScript Code
function RP()   
{   
    = 1;   
    = function()   
    {   
         alert(“ ”);   
    };   

    = 100;    
    = function()   
    {   
         alert(“”);   
    };   
}   

= 10;    
= function()   
{   
    alert(“”);   
};   
//The following execution
rp = new RP();   
alert();//Warning result is: 1
();//The warning result is:
alert();//Warning result is: 100
();//The warning result is:
delete ;   
alert();//The warning result is: undefined

delete ;   
alert();//Warning result is: 100
delete ;   
();//The warning result is:
Let’s look at another one with parameters to calculate the area of ​​the circle:

JavaScript Code
        <script type=“text/javascript”>   
function Circle(x,y,r){       
  = x;       
  = y;       
  = r;       
// = null ;     /*This code can be regarded as implicitly, because there is no difference in the definition of "class" in javascript and the definition of function, so it can be said that all functions have such an attribute hidden. */
}   
=function(){   
    return **3.1415926;   
}   
var Circ=new Circle(0,0,5);   
alert(parseInt(()));   
        </script>