Context invocation Pattern
You can modify the value of this, that is, you can modify the function call method, apply, call can modify the function invocation context, that is, the value of this
<Script> varname= "Leonardo's self-reliance and Guo"; functionSayHello (A, b) {Console.log ( This. Name+ "Eat the" +(A*b)+ "a steamed bun"); } varobj={name:"Nicholas Electric Rice and pot" } vararr= [Ten, -]; Sayhello.apply (obj, arr);//Nicholas Electric rice and pot ate 200 steamed bunssayhello.call (obj,2, 3);//Nicholas Electric Rice and pot ate 6 steamed buns</Script>
The difference between apply and call
function. Apply (object, [function requires parameter list, is an array])
function. Call (object, ARG1,ARG2,ARG3...ARGN)
The specific difference is that the Apply parameter is an array, and the parameter of the call pass in function is a value of a value of the way, so according to their characteristics, the use of the situation is also different:
1, apply for the function of the number of parameters of the case of uncertainty
2. Call is used to determine how many parameters of a function are used
Case analysis
(1) To find the maximum value of an array
<Script> vararr= [9, 1, 4, Ten, 7, A, 8]; //the second argument to the Apply method is an array //at the time of invocation, each element in the array is taken out as a formal parameter, passed to the function //when the first argument of the Apply method and the call method passes NULL, it is represented as a function invocation pattern //That is, point this to window varMax=Math.max.apply (NULL, arr); //==> equivalent to Math.max (9,1,4,10,7,22,8)Console.log (max);// A</Script>
(2) Print the passed in parameters and connect with '-'
<Script> functionfoo () {//the pseudo-array does not have a join method, so it is time to consider borrowing the array join method //var str = Array.prototype.join.apply (arguments,["-"]); varStr=[].join.apply (arguments, ["-"]); returnstr; } varStr=Foo (1, 3, "ABC", "FFFF", About) //1-3-abc-ffff-99Console.log (str);</Script>
(3) Set the color of div and P tags
<Script> vardivs=document.getElementsByTagName ('Div'); varPS=document.getElementsByTagName ('P'); vararr= []; Arr.push.apply (arr, divs); Arr.push.apply (arr, PS); for (varI= 0; I<arr.length; I++) {Arr[i].style.backgroundcolor= 'Yellow'; }</Script>
JS Advanced--Context mode