Use of 1.apply, call changes the This object
Apply and call use function person (age,sex) {this.age=age;this.sex=sex;} Add a method through the prototype person.prototype.sayhi=function (x, y) {console.log ("hello" +this.sex); return 1000;} var person=new person (10, "male");p erson.sayhi ();//function Student (name,sex) {this.name=name;this.sex=sex;} At this time the problem of the prototype object is changed, Var stu=new Student ("Xiao Ming", "shemale"), var r1=person.sayhi.apply (stu,[10,20]);//Changed the This object adds Stu object var to sayhi R2=person.sayhi.call (stu,10,20);
2.apply and Call Usage Summary
How to use the Apply and call/* * Apply using the syntax * function name. Apply (object, [Parameter 1, Parameter 2,...]); * Method name. Apply (object, [Parameter 1, Parameter 2,...]); * Call's use syntax * function name. Call (object, parameter 1, parameter 2,...); * Method name. Call (object, parameter 1, parameter 2,...); * * Function: Change the direction of this * different places: The parameter is passed differently * * As long as you want to use a method of another object, and you want this method to be the current object, you can use apply or call method to change the point of this * * Both *///apply and call can change the pointer//function of this, changing the point of this function F1 (x, y) { Console.log ((x+y) + ":===>" +this); Return "This is the returned value of the function"; }//apply and call var r1=f1.apply (null,[1,2]);//This in F1 is the window cons Ole.log (R1); var r2=f1.call (null,1,2);//This is the window in F1 Console.log (R2); Console.log ("=============>"); Change this to point to Var obj={ Sex: "Male"}; The F1 function was originally a Window object, but after it was passed into obj, the F1 function is now the Obj object's var r3=f1.apply (obj,[1,2]);//This in F1 is the obj console . log (R3); var r4=f1.call (obj,1,2);//The This in F1 is the obj console.log (R4);
JS in the Apply and call methods