The ECMAScript specification defines call () and apply () two methods for all functions, and the first parameter of call and apply is the function object that needs to be called, and in the function body This parameter is the value of this, and the remaining arguments are the values that need to be passed to the function. The difference between call and apply is that the value of call can be arbitrary, and the remaining value of apply must be an array.
For example:
function return A + b;} function return A- b;} /* Apply Usage * var a1 = sub.apply (Add, [4, 2]); *var a2= add.apply (Sub, [4, 2]); */ var a1 = Sub.call (Add, 4, 2); var a2= Add.call (Sub, 4, 2); output: A1=2 a2=6
The feeling is still intentional, more interesting is still below
JS always think he is omnipotent, since the high-level language will inherit, I JS can not be weak: JS imitation inheritance
functionfun1 () { This. A = 123; This. Add =function() {return This. A}}functionfun2 () { This. A = 456;}varf1=Newfun1 ()varF2=Newfun2 ()varA = F1.add.call (F2);//a The output is 456
Here is the F1 method to F2 to use, F2 can use all the methods in F1, this is not the concept of high-level language inheritance. Of course, depending on how many inheritance can be extended, multiple call can be used to achieve multiple inheritance
functionfun1 () { This. Add =function() {return This. A + this.b}}functionfun2 () { This. Sub =function() {return This. A- This. B}}functionFun3 () { This. A = 10; This. B = 2; Fun1.call ( This); Fun2.call ( This);}varF3 =Newfun3 () alert (F3.add ()); alert (F3.sub ());
JS call () apply ()