call methods and apply methods

1.call

grammar

call([thisObj[,arg1[, arg2[, [,.argN]]]]])

parameter

thisObj options. It will be used as the current target object.

arg1, arg2,, argN options. Method parameter sequence is passed.

Explanation

The method may be used instead call another object calls a method. The method may call a function of the object context specified by the new object from the initial thisObj context change. If no thisObj parameters, then the Global object is used as thisObj.

2.apply

grammar

call([thisObj[,arg1[, arg2[, [,.argN]]]]])

parameter

thisObj options. It will be used as the current target object.

argument [] array, the method parameter is passed

Explanation

apply and call the function almost the same, meaning the first argument are the same, but the second parameter passed is a little different apply a parameter array, which is a combination of multiple parameters to be passed in an array, the second call from argument began, followed by the value of the parameter passed to the called function 

3.call difference method and apply methods

The same point : effect produced by the two methods are exactly the same, are used to change the current subject function calls.

Different points : the different parameters of the call:

// The following three lines the same effect 
foo.call (this, arg1, arg2, arg3) == foo.apply (this, arguments) == this.foo (arg1, arg2, arg3)

And apply methods of action 4.call

Role call method

  1. Modify this point

  2. Inheritance

//例1
    window.color = 'red';
    document.color = 'yellow';
    var s1 = {color: 'blue' };
    function changeColor(){
         console.log(this.color);
    }
    changeColor.call();         //red (默认传递参数为globalObj)
    changeColor.call(window);   //red
    changeColor.call(document); //yellow
    changeColor.call(this);     //red
    changeColor.call(s1);       //blue
//例2
    var Pet = {
        words : '...',
        speak : function (say) {
            console.log(say + ''+ this.words)
        }
    }
    Pet.speak('Speak'); // 结果:Speak...

    var Dog = {
        words:'Wang '
    } 

    // change to this point would be Dog 
    Pet.speak.call (Dog, 'Speak'); // Results: SpeakWang 
// Example 3
  function FriendA(name){
   this.name=name;
  this.say=function () {
   console.log('hello');
  }
  }
  function FriendB() {
   console.log(this);
  FriendA.call(this,'lucy');
  console.log(this);
  }

 Example 3 Console:

FriendB inherits the methods and properties of FriendA

 

Guess you like

Origin www.cnblogs.com/daiSir/p/11242543.html