Home > Article > Web Front-end > Understanding apply and call of functions in JavaScript_javascript skills
JavaScript function calls are divided into 4 modes:
1. Method calling mode: that is, the object contains method attributes, Obj.methodName() or Obj[methodName]().
2. Function calling mode: methodName().
3. Constructor calling mode: new MethodName().
4. Apply and call calling modes: ObjA.apply(ObjB,args[]) or ObjA.call(ObjB,arg1,arg2...).
When a function is called, in addition to receiving formal parameters, it also receives this and arguments. Among them, this is the function object context and arguments are the actual parameters.
Apply and call implement the same function, that is, switching the context of the function object (the reference pointed to by this). The difference is that the formal parameters are different. apply is arguments or an array, call is multiple individual formal parameters separated by commas.
function add(c) { alert(this.a+this.b+c); } var test={a:1,b:2} add.call(test,3);
Before executing add.call(test,3);, both add and test belong to window, and this points to window at this time. add.call(test,3); When executing, enter the add method body. At this time, this is switched from window to test. At this time, this.a=test.a, this.b=test.b, and c are passed in as formal parameters. The value of alert() is 1 2 3=6. apply also has the same function.
Extension and inheritance through apply and call:
function Animal(name){ this.name = name; this.showName = function(){ alert(this.name); } } function Cat(name){ Animal.call(this, name); } var cat = new Cat("Black Cat");//执行时,Cat函数体的this由window切换为Cat{}, // Animal函数体的this.name通过形式参数传入即为Black Cat,最终cat //得到的结果为cat=Cat{name:"Black Cat",showName: function(){ alert(this.name);}, cat.showName();//执行时this由window切换为 //Cat{name:"Black Cat",showName: function(){ alert(this.name);} 此时this.name //为this.name=Cat.name,因此为Black Cat。