Apply and call are important methods in JavaScript, and although programming is seldom accessible, the JS framework uses these 2 methods everywhere.
These 2 methods are in Function.prototype, which means that each JS function has these 2 methods.
Alert (Function.prototype.hasOwnProperty ("apply"));//truealert (Object.prototype.hasOwnProperty ("Apply");// False
The functions performed by these 2 functions are equivalent and the only difference is in the form of parameters.
function Person (name,age) { alert ("name=" + name + ", age=" +age);} Person.call ({}, "Aty", 10); Person.apply ({},["Aty", 10]);
detailed description of the method https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Function
The code for invoking a method through reflection in Java is as follows:
method = Clazz.getdeclaredmethod ("say"); Method.invoke (clazz.newinstance (), NULL);
You can see that the Java reflection method call is very similar to Apply/call. The person is equivalent to method, which represents what methods are called, {} and Clazz.newinstance () are similar to which object is called (that is, this in the method), and the last is the parameter list required by the method.
We know that in Java the This keyword represents the current object, we cannot modify it, and the function is called directly in JavaScript, just like a Java function call, which represents the current object.
If you want to modify this, you can use apply this way.
Aobj. afunction ("1");
Aobj.afunction.apply (bobj,["1"]);
The first way, the this in the function is Aobj, which is something we are more familiar with, and the second way, the this in the function is bobj.
With apply, object bobj can use the methods defined in aobj .
function Functiona (name) { this.name=name; } function functionb (name,age) { functiona.apply (this,arguments); This.age=age; }
using the F12 debugging tool, you can discover that the Bobj object has the name and age properties.
Learn about the apply and call in JavaScript