call apply bind usage

In Javascript, call, apply and bind a Function object carrying three methods, this method three primary role is to change the function of this point.

apply ,  call , bind Three points are used to change the function of this object;
apply ,  call , bind three first argument is to point to this object, that is, you want to specify the context (Each call function has a special value - the call context (context) - this is the thisvalue of the key);.
apply ,  call , bind all three parameters can be used subsequent parameter passing;
bind return the corresponding function, to facilitate later call; apply , call then the call is immediately 

call();

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

Definition: a method call to an object, another object to replace the current object

Description: call method can be used in place of another object invoke a method

The method may call a function of the object context specified by the new object from the initial thisObj context change

thisObjValues following four cases:
(1) does not pass, or pass null, undefined, this refers to the function of the window object
(2) the transfer function of another function name, the function of this function reference point
(3 ) passing strings, numeric or Boolean type of base type, the function of this point to the corresponding object to be packaged, such as string, Number the, Boolean
(. 4) passing an object, the function of this object point

function a(){   
  console.log(this); //输出函数a中的this对象 } function b(){} var c={name:"call"}; //定义对象c a.call(); //window a.call(null); //window a.call(undefined); //window a.call(1); //Number a.call(''); //String a.call(true); //Boolean a.call(b); //function b(){} a.call(c); //Object

function class1(){   
  this.name=function(){ console.log("我是class1内的方法"); } } function class2(){ class1.call(this); //此行代码执行后,当前的this指向了class1(也可以说class2继承了class1) } var f=new class2(); f.name(); //调用的是class1内的方法,将class1的name方法交给class2使用
例子:
function eat(x,y){   
  console.log(x+y); } function drink(x,y){ console.log(x-y); } eat.call(drink,3,2) //5


function Animal(){   
  this.name="animal"; this.showName=function(){ console.log(this.name); } } function Dog(){ this.name="dog"; } var animal=new Animal(); var dog=new Dog(); animal.showName.call(dog); 输出:dog








Guess you like

Origin www.cnblogs.com/qingcui277/p/10412984.html