JS in Call and apply

Source: Internet
Author: User

Role:

Replaces this in the method of the current object.

Understand:

Call and apply are used to dynamically change The this occurrence, when an object does not have a method, but others have, we can use call or apply the method of other objects to operate.

The DOM node chosen by document.getElementsByTagName is a type of array that is similar to array.

It cannot apply methods such as Push,pop under the array. We can do this by:

var domnodes = Array.prototype.slice.call (document.getElementsByTagName ("*"));

This allows the domnodes to apply all the methods under the array.

Grammar:

Call ([thisobj[,arg1[, arg2[, [,. ArgN] ]]) # #没提供thisObj, the Global object will be used as a thisobj. Parameters are separated by commas.

apply ([Thisobj [, Argarray]]) # #没提供 Thisobj, the Global object will be used as a thisobj. The parameter is an array, and the main difference from call is in the Parameter form, so if the number of parameters can be determined by call, if the number of arguments is indeterminate, apply.

Skills:

1. Convert arguments to arrays

function Args2arr () {    return [].slice.call (arguments, 0);     // return Array.prototype.slice.call (arguments, 0);   The same effect as the top }args2arr (1, 2, 3, 5, 6, 7, 8);   // [1, 2, 3, 5, 6, 7, 8]
arguments object: The object represents the function being executed and the parameters of the function that called it. You cannot explicitly create an arguments object. The arguments object is available only when the function starts. The arguments object of a function is not an array, and a single parameter is accessed in the same way as an array element. Slice: Returns a segment of an array. Arrayobj.slice (start, [end]) [Start is the starting subscript, end is the subscript ending, end is not length]so [].slice.call (arguments, 0) is the slice method that called the array, but the object is replaced with the arguments, and the start parameter 0 is passed in to slice all the arguments into a new array.

2. Returns the maximum value in the array

function Argsmax () {    //  Find out the maximum number of values in the arguments of the object    return Math.max.apply (null  , arguments);} Argsmax (1, 2, 3, 5, 6, 7, 8)  //  8

Math.max([number1[, number2[. . . [,numberN]]]]) : Returns the larger of the 0 or more numeric expressions given.

Max itself receives a comma-delimited parameter, passing in an array of parameters through the Apply method, the first parameter gives a null, this is because there is no object to call this method, I just need to use this method to help me to calculate the return of the result on the line,. So directly passed a null past.

3. Merging of two arrays

var arr1=New Array ("1", "2", "3"); var arr2=New Array ("4", "5", "6"); Array.prototype.push.apply (ARR1,ARR2);

arrayObj.push([item1 [item2[. . . [itemN ]]]]) : Adds a new element to an array and returns the new length value of the array.

Here arr1 as an object of the push method that hijacked the array, passing ARR2 as a parameter.


Example:

1. Borrowing functions

function GetName () {    returnthis. name}var obj = {name: "Jack"}; The function in Getname.call  (obj)//Jack,js is actually an object, and the function name is a reference to a function object. 

2. Method of borrowing objects

var obj1 = {    "Panxuepeng",    function() {return this . Name}} var obj2 = {name: "Jack"};obj1.getname.call (obj2)  //Jack

3. Slightly more complex objects

 //constructor, the corresponding object is animal.  functionAnimal () { This. Name = "Animal";  This. ShowName =function() {alert ( This. Name); }        }              functionCat () { This. Name = "Cat"; }               varAnimal =NewAnimal (); varCat =NewCat (); Animal.showName.call (CAT); //Cat, the method in the calling object must first instantiate the class    /** The method of calling the animal object ShowName must first instantiate the animal class, if just call properties * can be directly animal.property on the line * so the top of the written Animal.showName.call will be error /c5>*/        //animal.showName.apply (cat,[]); 

4. Inheritance

    functionAnimal (name) { This. Name =name;  This. ShowName =function() {alert ( This. Name); }          }                  functionCat (name) {Animal.call ( This, name); }                  varCat =NewCat ("Black cat");  Cat.showname (); //Black Cat

JS in Call and apply

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.