and apply the function call javascript

The method of the call so that the current javascript object can call another object method, i.e. directed to change the content of this

 1 var first_object = {
 2 num: 42
 3 };
 4 var second_object = {
 5 num: 24
 6 };
 7 function multiply(mult) {
 8 return this.num * mult;
 9 }
10 alert(multiply.call(first_object, 5)); // 210
View Code

This will return the execution result, 210. First_object can be seen in this becomes the current object first_object in this. And first_object have all the methods and properties of the current object.

Use call function is:

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

thisObj

Selected object

arg1,arg2..argN

Optional. Method parameter sequence is passed.

 1 function Class1() 
 2 { 
 3     this.name = "class1"; 
 4 
 5     this.showNam = function() 
 6     { 
 7         alert(this.name); 
 8     } 
 9 } 
10 
11 function Class2() 
12 { 
13     this.name = "class2"; 
14 } 
15 
16 var c1 = new Class1(); 
17 var c2 = new Class2(); 
18 
19 c1.showNam.call(c2); 

call means that the method c1 c2 is placed on execution, originally c2 is not showNam () method, is now the c1 of showNam () method to perform up into c2, so this.name should be class2, the results of implementation is : alert ( "class2"); 

 

You can also use call inheritance

the Class1 function () 

    this.showTxt = function (TXT) 
    { 
        Alert (TXT); 
    } 


function Class2 () 

    Class1.call (the this); 


var new new Class2 = C2 (); 

c2.showTxt ( "CC") ; 

this Class2 inherits the Class1, Class1.call (this) means that the use of Class1 objects instead of this object, then the Class2 not have all the properties and methods of Class1 yet, c2 will be able to call the object's methods and properties directly Class1 the execution result is: alert ( "cc"); 

 

apply () function and call () function is the same, except that the first parameter with two arguments apply a first parameter and call () is the same, the second parameter is an array.

Reproduced in: https: //www.cnblogs.com/mole/p/3994824.html

Guess you like

Origin blog.csdn.net/weixin_33744141/article/details/93227684