1.call ()
Syntax:obj1.call (obj2[,param1,param2,...])
definition: use Obj2 object instead of Obj1, call obj1 method. The obj1 will be applied to the OBJ2.
Description:The call method can be used to invoke a method in place of another object. The call method can change the object context of a function from the initial context to a new object specified by Obj2. If the OBJ2 parameter is not provided, then the Global object is used as the obj2.
2.apply ()
Syntax: Obj1.call (Obj2[,arrarg])
Definition: Use Obj2 object instead of Obj1, call obj1 method. The obj1 will be applied to the OBJ2.
Note: Call () is the same as apply (), but call () can receive parameters of any type, and apply () can only receive array parameters.
3. Basic usage[JavaScript]View PlainCopy print?
- function Add (A, b) {
- return a+b;
- }
- function sub (c,d) {
- return c-d;
- }
- function result () {
- this.addvalue = null;
- this.subvalue = null;
- this.showresult=function () {
- Alert (this.addvalue);
- Alert (this.subvalue);
- }
- }
- var r = new result ();
- R.addvalue = Add.call (sub,4,2); //6, apply the Add method to the sub, which is the pointer to the sub that points to the Add method
- R.subvalue = Sub.call (add,4,2); //2, replacing the sub object with the Add object, and invoking the method of the Sub object
- R.showresult (); //In JS The function is also a functions object, the function name is the object reference
4. Inheritance Features[JavaScript]View PlainCopyprint?
- function Add (A, b) {
- return a+b;
- }
- function sub (c,d) {
- return c-d;
- }
- function result () {
- this.addvalue = null;
- this.subvalue = null;
- this.showresult=function () {
- Alert (this.addvalue);
- Alert (this.subvalue);
- }
- }
- var r = new result ();
- R.addvalue = Add.call (r,4,2); //6,r inherit all the attributes of the Add function
- R.subvalue = Sub.call (r,4,2); //2,r all features of the integrated sub function
- R.showresult ();
The call () and apply () methods in JS