In-depth understanding of Js's prototype and some applications of prototype

Source: Internet
Author: User
Tags shuffle

The previous article tells the prototype concept of js, and here is a review of the definition of prototype:

Prototype is a property of a function and is a prototype object of a Function. It is necessary to refer to the function, which should be remembered.

but, It's strange, crossing, have you ever seen a JS code that references prototype like This:

function func () {    var args = Array.prototype.slice.call (arguments, 1);     return args;}

Hey??? Looking at the above line of code, do you have a deep suspicion that prototype just belongs to the function?

Do you understand the meaning of the above function? I'll explain it to you.

Call is a method of function, and for this method, it is only function Before it can be called, it does this by invoking a function that references it.

Take this Array.prototype.slice.call (arguments,1), here the bread contains too much information, I analyze it one by one.

Slice (start[,end]) is a native array function of JS that takes the elements from the start subscript to the end of the end in the Array. As an example:

var arr1 = [2,3, ' l ', 4,5, ' J ', ' I '];    Alert (arr1.slice (1)); // End subscript ellipsis means intercept from start subscript to end   // here the alert is 3, ' L ', 4,5, ' J ', ' I ', you can try it yourself

Arguments is a property of the JS function object that gets the argument of the function and returns an object with the function argument as the property Element. As an example:

function args () {    returnthis. arguments;   Here's This can be omitted, you can try it    // I add it to illustrate that the call arguments can only be object }alert ( Json.stringify (args (1,3,5,6,8))); // the returned {"0": "1", "1": "3", " 2": "5", "3": "6", "4": "8"}

About the object properties of the function arguments so much to say here, to understand in detail, can BAIDU.

The array is the keyword that generates the arrays in Js.

Why do we use Array.prototype to invoke the slice function? Instead of array.slice, the reason is simple because the Array's keyword array cannot be called array.xx directly to the JS array Function. But why not just call it that way? No hurry, Let's do the experiment next, you will be very clear.

Alert (array.slice ()); // uncaught TypeError:Array.slice is not a function

 Here directly to give you an error, explain what? well, This means that the array keyword does not directly call the function of the Arrays.

Alert (json.stringify (array.prototype)); alert (json.stringify (Array.prototype.slice ()));

  All returned here are empty arrays ... [], what does it explain?] It is explained that the array keyword really can call the properties of the prototype function, and it also shows that JS is an array function that can call JS Array.prototype.

Speaking of this, the problem is coming, I am not saying that prototype is a property of the JS function, can only be called by the function? What is the array keyword here that can call this property prototype? so, I'm Not in the hole. is the definition of prototype wrong? I'm not here to face myself? hey, crossing, yes, You see right Here. however, As for the array keyword can call the function of the prototype property, I did not give myself a face, here, we do not rush to the Conclusion.

Turning a bend to say, crossing remember how JS generates arrays in several ways? There should be a variety, but I'm not going to introduce you here.

But have you seen how to generate arrays like this? Let's start by looking at the following code:

var New Array ();

This way to generate arrays remember? so, can our JS function also generate objects like this?

function func () {} var New func ();

  How does the above build an array and the following constructor generate the object in a way that is not very similar? yes, JS in the function and array are can be generated through new objects such things, which shows what? Do you see that array () and Func () are very similar? Is there a pair of parentheses at the back? Is right, hehe, said so much, I just want to expose one thing, this thing is, if I guess not wrong, Array () this thing is actually JS a Construct the built-in function of an array-otherwise, the way you can live an array with the new array () is not justified, is it?

In this case, we return to say JS can be so array.prototype call prototype it is clear, right? Array () is a built-in function of js, since array is a function, then the array must have prototype this property, right? so, the array keyword call prototype does not violate prototype is a property of the function of this principle, prototype is a function of a property is still a constant conclusion.

about how arrays are generated, similar to whether we can generate an object like this in the new object (), or create a string like the new string ()? Now that we can construct the object and the string, the following code should be possible, right?

Alert (json.stringify (string.prototype)); Alert (json.stringify (object.prototype));

According to the above explanation, you should know that this can be done, right? You should know how this is going to work out, right? You try it yourself. This is no longer explained Here.

Speaking of which, hey, since I have to write the beginning of the function to forget? Here's how the Func function works at the beginning of this article:

The function of the Func function is to get the arguments of the Func function starting from the second real Argument.

Let me analyze it for you:

function func () {var args = Array.prototype.slice.call (arguments, 1); return args;} Alert (func (0,1,2,3,4)); // to pass arguments to the Func function

 Array.prototype is an empty array,

Array.prototype.slice () means an empty array called an array of functions slice (),

Array.prototype.slice.call () means that the call function calls an array of functions slice (),

Here call () how to invoke Slice ()?

This is the case, arguments gets the func function argument list, generates an object to pass to the call () function, and the call function passes the arguments generated object to the empty array of array.prototype, and the second parameter ... 1 Passed to the slice function, and then call lets the function referencing it slice execute slice (1), so slice starts to get the elements of the array from the 1 subscript, and the elements of this array are actually arguments elements, so The function of Func is to get all the arguments that start with the subscript 1. Don't believe, you can execute the above function yourself.

Here are the prototype Applications:

Application 1:

Adding a function to a prototype object is to have the object have a common Function.

Example: I add a scrambled array method to the array prototype Object:

//Add a function that disrupts the array to the array prototypearray.prototype.shuffle=function(){varValue = this. valueOf (), len = this. length,temp,key; while(len--){//randomly generated subscript for an arrayKey = Math.floor (math.random () *len);//temp is the middle swap variabletemp =value[key];value[key]=value[len];value[len]=temp;}returnvalue;}varARR1 = [0,1,2,3,4,5,6,7,8,9];varARR2 = [' a ', ' b ', ' C ', ' d ', ' e ', ' f ']; Alert (json.stringify (arr1.shuffle ())); alert (json.stringify (arr2.shuffle () ));

You can try adding an array arr3 to see if it can call the shuffle function, because I'm adding a function to the Array's prototype object, so within this script, all the arrays have shuffle Function.

Application 2:

Adding properties to a prototype object, that is, adding common properties to the object

Example:

function fun () {        = ' small East '= [1,2,3,4];   The property can be an array, or it can be the object varnew fun (); var New Fun ( ); alert (json.stringify (ob1.name)); alert (json.stringify (ob2.arr)) ;

Application 3:

Implementation of prototype inheritance;

    functionP1 () {}functionP2 () {}//prototype objects Add properties and methodsP2.prototype.name = ' P2 ' s name '; P2.prototype.get=function(value) {returnValue; }    //instantiate an object of the P2 constructor    varOBP2 =NewP2 ();//This object should contain the properties and methods of all prototype objects    //assigns an object to P1 's prototype object, equivalent to P1 inherits all the properties and methods of OBP2P1.prototype = obp2;//this equation, in simple terms, is like a = b, B assigns a value to A.     //call P1 The Get function inherited from obp2.Alert (P1.prototype.get (' out ' s name '))); //Show P1 the Name property inherited from Obp2Alert (P1.prototype.name); //instantiating a Obp1 object with a constructor P1    varOBP1 =NewP1 (); //P1 's prototype object prototype since all the properties and functions of OBP2 have been inherited, then the objects instantiated by P1 have OBP2 properties and Functions.Alert (obp1.get (' OBP1 "s name));

About prototype here, If there are any errors in this article, but also hope that you crossing pointed out that I am good to Correct.

noted in Particular:

Array.prototype is an array

String.prototype is a string

Object.prototype is an object

These three special examples, unlike the prototype of a constructor, of course, if you really understand that prototype is a prototype object of a function, you should know that the prototype object of an array should be an array, not an object? The prototype object of a string should be a string and not an object, right?

In-depth understanding of Js's prototype and some applications of prototype

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.