In the learning of new things, have seen before and do not understand, or memory is not deep places may wish to look back at the book Knowledge points, help deepen understanding. It is so-called--wen Xin.
Nonsense not much to say, directly on the code:
The first section: a simple example
function Add (b) { Console.log (a+b); } function Sub (b) { console.log (a-b); } Add.call (Sub,3,2); 5
Summary: The above code defines two methods, and in the last word, it may be understood that a sub object calls the method of the Add object and takes the parameters into the method.
section II: In-depth understanding of call and apply
The definition of call and apply is a non-inheriting method of a function that calls a function within a specific scope, sets the value of the This object in the function body,
function Njie () { this . Name = "Njie" this . Saynam E = function () {Console.log ( this .name); }} function KK () { this . Name = "KK" ; var n = new Njie (); var k = new KK (); N.sayname (); Njie N.sayname.call (k); KK
Summary: For example: K object does not have Sayname function, and n has this function, that k by call to borrow N sayname use, of course, also to the value in K into the method.
Section III: The difference between call and apply
Description: The difference between call and apply is that the two incoming parameters are different in the same way
//Parent Class functionPerson (name,age) { This. Name =name; This. Age =Age ; } //sub-class students functionStudent (Name,age,grade) {person.apply ( This, arguments);//subclass inherits the parent class //Person.call (this,name,age); Of course, you can also use the call method This. grade =grade; } //create an instance of a student varS1 =NewStudent ("Nujie", "23", "Peking University adult class, first grade"); Console.log ("Hello,", S1.name, "You this year", S1.age, "year-old, study in", S1.grade, ", really great");
Summarize:
The above example has two points:
1, it is possible to use the call method to do the inheritance of JS processing;
The difference between 2,call and apply is mainly in the following parameters, call parameters to list the parameters, and apply can use arguments this property directly with the past.
About the use of call and apply understanding in JS