call, apply and bind usage resolve

The JavaScript function is an object, an object can be called. It is a sub-type of the function object. typeof functionName === "object"Also illustrates this point. Function object can contain methods, is call, apply and bind method functions we have to discuss today.

  • Any function can be used as a method to call any object, even after this method is not the function of that object, the object as a function of the method call inside a function this points to the object to be bound.

  • call and apply methods seen as an object, in the form of method call to call functions indirectly.

  • call () and apply () The first argument is the function to call the parent object is, different from these two methods is that a different form of parameter passing.

  • call () in addition to other parameters than the first parameter value is passed to the called function to be.

  • apply () function call parameters passed in an array.

  • The main role of this bind method binds a function to an object. When the call of the function f bind () on () method and passing an object o as a parameter, this method returns a new function. The new function will call the original function f () o as a way to call. Any arguments passed in the new function will be passed the original function. Incoming bind () arguments will be bound to this.

Examples of the method call and apply:

//要想以对象o的方法调用函数f(),并传递参数1,2,可以这样做:
var o = { a : 1 }
function f( x , y ){
	console.log( this.a + x + y )
	return 124
}
//f()函数被执行,this指向对象o,this.a === 1
f.call(o,1,2); //4
//返回值是函数的返回值
var result = f.call(o,1,2) //result === 124
f.call(o,1) //NaN ,未传入y,y为undefined
//调用的对象方法不变
console.log(o); //{a:1}
console.log(o.f === f); //false
f.apply(o,[1,2]); //4

call application, call the join method of the string array directly:

//join:将数组的元素根据传入的参数进行拼接返回拼接后的字符串
var a = "foo";
//直接调用时字符串没有join方法
console.log(a.join); //undefined
 //通过call去调用Array对象的方法
var c = Array.prototype.join.call(a, "-");
console.log(c); //f-o-o

bind method Example:

var sum = function(x, y) {
  console.log(this.a, x, y);
  return this.a + x + y; //this由调用时决定,由下文可知,this指向o对象
};

var o = { a: 1 };

var targeFun = sum.bind(o, 2); //2传入到 x 位置,下面调用传入的3 传入到 y 位置
var m = targeFun(3); //1,2,3
console.log(m); //6

By call method, we can go to call different variable types has different methods of context.


Reference:
JavaScript Definitive Guide

Published 18 original articles · won praise 10 · views 616

Guess you like

Origin blog.csdn.net/llq886/article/details/104220915