2013年9月24日星期二

the javascript call and apply methods

 

we can call and apply seen as an object method , by calling the method in the form of indirect function call . call and apply the first argument is the function to call the parent object, which is the calling context , the in vivo function through this to get a reference to it .

 

example, if you want to object o way to call a function f, can be used as a way call and apply methods :

 

f.call (o);

 

f.apply (o);

 

can be understood by the following code :

 

om = f; / / will be stored as o f a temporary method

 

om (); / / call this temporary method

 

delete om; / / will delete this temporary method

 

come to sample it.

 

function testFun () {

 

return this.a + this.b;

 

}

 

var o = {a: 1, b: 2};

 

testFun.call (o); / / 3

 

testFun.apply (o); / / 3

 

result of the implementation of the code are three , can be understood as return oa + ob.

 

considered a problem , call and apply methods if the first argument is null or undefined to what ? Consider the following example :

 

var a = 10, b = 20;

 

function testFun () {

 

return this.a + this.b;

 

}

 

testFun.call ();

 

testFun.apply ();

 

result of the implementation of the code is 30 . This is because the call and apply the first argument passed is null or if undefined, it will be the global object instead.

 

that these two methods call and apply what difference does it ?

 

method for the call , the first argument after calling context of all the arguments is to pass the value of the function to be called . For example, a method in the form of object o call the function f, and pass two parameters , you can use the following code :

 

f.call (o, 1, 2);

 

method which will apply after the first argument into an array of all the arguments within ,

 

f.apply (o, [1, 2]);

 

to you an example

 

function testFun (x, y) {

 

return this.a + this.y + a + b;

 

}

 

var o = {a: 1, b: 2};

 

testFun.call (o, 10, 20);

 

testFun.apply (o, [10, 20]);

 

results of the implementation of the code is 33 , can be understood as a return oa + ob + 10 + 20

 

没有评论:

发表评论