Home  >  Article  >  Web Front-end  >  Detailed explanation and summary of call, apply, and bind methods in Javascript

Detailed explanation and summary of call, apply, and bind methods in Javascript

巴扎黑
巴扎黑Original
2016-12-22 13:51:451400browse

The following content will be divided into the following sections:

1. The source of the call/apply/bind method

2.Function.prototype.call()

3.Function.prototype.apply()

 3.1: Find the array The maximum number in

 3.2: Change the empty element of the array to undefined

 3.3: Convert an array-like object

4.Function.prototype.bind()

5. Bind the object of the callback function

6. The connections and differences between the call, apply, and bind methods

1. The origin of the call/apply/bind method

First of all, when using the call, apply, and bind methods, it is necessary for us to know where these three methods come from? Why can these three methods be used?

The three methods call, apply, and bind are actually inherited from Function.prototype and are instance methods.

console.log(Function.prototype.hasOwnProperty('call')) //true
console.log(Function.prototype.hasOwnProperty('apply')) //true
console.log(Function.prototype.hasOwnProperty('bind')) //true

In the above code, true is returned, indicating that the three methods are inherited from Function.prototype. Of course, ordinary objects, functions, and arrays all inherit the three methods in the Function.prototype object, so these three methods can be used in objects, arrays, and functions.

The concept of inheritance will be shared with you in the future.

2.Function.prototype.call()

The call method of a function instance can specify the pointer of this inside the function (that is, the scope in which the function is executed), and then call the function in the specified scope . And the function will be executed immediately.

Look at an example to understand this passage better.

var keith = {
rascal: 123
};
var rascal = 456;
function a() {
console.log(this.rascal);
}
a(); //456
a.call(); //456
a.call(null); //456
a.call(undefined); //456
a.call(this); //456
a.call(keith); //123

In the above code, if the this keyword in the a function points to the global object, the return result is 456. It can be seen that if the call method has no parameters, or the parameters are null or undefined or this, it is equivalent to pointing to the global object. If you use the call method to point the this keyword to the keith object, that is, the scope in which the function is executed is the keith object, the return result is 123.

The call() method can pass two parameters. The first parameter specifies the pointer of this inside the function (that is, the scope in which the function is executed), and the second parameter is the parameter that needs to be passed when the function is called.

function keith(a, b) {
 console.log(a + b);
 }
keith.call(null, 1, 2); //3

The first parameter is required and can be null, undefined, this, but cannot be empty. Set to null, undefined, this indicates that the function keith is in the global scope at this time. The second parameter must be added one by one. In apply, it must be added in the form of an array.

One application of the call method is to call the native method of the object. Can also be used to convert array-like objects to arrays.

var obj = {};
 console.log(obj.hasOwnProperty('toString')); //false
 obj.hasOwnProperty = function() {
 return true;
 }
 console.log(obj.hasOwnProperty('toString')); //true
 console.log(Object.prototype.hasOwnProperty.call(obj, 'toString')); //false

In the above code, hasOwnProperty is a method inherited by the obj object. If this method is overridden, the correct result will not be obtained. The call method can solve this problem. It puts the original definition of the hasOwnProperty method on the obj object for execution, so that regardless of whether there is a method with the same name on obj, it will not affect the result. It should be noted that hasOwnProperty is a method of the native object of Object.prototype, and call is a method inherited from Function.prototype.

3.Function.prototype.apply()

The apply method is similar to the call method. It also changes the point of this (the scope where the function is executed), and then calls the function in the specified scope. The function will also be executed immediately. The only difference is that it receives an array as a parameter when the function is executed. The first parameter of the

apply method is also the object that this points to. If it is set to null or undefined or this, it is equivalent to specifying the global object. The second parameter is an array, and all members of the array are used as parameters in turn and passed into the original function when calling. The parameters of the original function must be added one by one in the call method, but in the apply method, they must be added in the form of an array.

Look at the nuances of call and apply.

function keith(a, b) {
 console.log(a + b);
 }
 keith.call(null, 2, 3); //5
 keith.apply(null, [2, 3]); //5

In the above code, the first parameter is null, pointing to the global scope; the second parameter is passed in a slightly different form.

apply method has the following applications.

3.1: Find the maximum number in the array

var a = [2, 4, 5, 7, 8, 10];
console.log(Math.max.apply(null, a)); //10
console.log(Math.max.call(null,2, 4, 5, 7, 8, 10)); //10 

Javascript does not provide a method to find the maximum value in the array. Use the apply and Math.max methods inherited from Function.prototype to return the array. the maximum value.

3.2: Change the empty element of the array to undefined

Use the apply method and use the Array constructor to change the empty element of the array to undefined.

console.log(Array.apply(null, [1, , 3])); // [1, undefined, 3]

The difference between empty elements and undefined is that the forEach method of the array will skip the empty elements. But undefined and null will not be skipped. Therefore, when traversing the inner elements, you will get different results.

var a = [1, , 3];
 a.forEach(function(index) {
 console.log(index); //1,3 ,跳过了空元素。
 })
 Array.apply(null,a).forEach(function(index){
 console.log(index); ////1,undefined,3 ,将空元素设置为undefined
 })

3.3: Convert an array-like object

In addition, using the slice method of the array object, you can convert an array-like object (such as arguments object) into a real array. Of course, an important application of the slice method is to convert array-like objects into real arrays. Both call and apply can implement this application.

console.log(Array.prototype.slice.apply({0:1,length:1})); //[1]
console.log(Array.prototype.slice.call({0:1,length:1})); //[1]
console.log(Array.prototype.slice.apply({0:1,length:2})); //[1,undefined]
console.log(Array.prototype.slice.call({0:1,length:2})); //[1,undefined]
function keith(a,b,c){
 return arguments;
 }
console.log(Array.prototype.slice.call(keith(2,3,4))); //[2,3,4]

The parameters of the call and apply methods in the above code are all objects, but the return results are all arrays, which serves the purpose of converting objects into arrays. As you can see from the above code, the premise for this method to work is that the object being processed must have a length attribute and a corresponding numeric key.

4.Function.prototype.bind()

bind方法用于指定函数内部的this指向(执行时所在的作用域),然后返回一个新函数。bind方法并非立即执行一个函数。

var keith = {
 a: 1,
 count: function() {
 console.log(this.a++);
 }
 };
 keith.count(); //1
 keith.count(); //2
 keith.count(); //3

上面代码中,如果this.a指向keith对象内部的a属性,如果这个方法赋值给另外一个变量,调用时就会出错。

var keith = {
a: 1,
count: function() {
console.log(this.a++);
}
};
var f = keith.count;
f(); //NaN

上面代码中,如果把count方法赋值给f变量,那么this对象指向不再是keith对象了,而是window对象。而window.a默认为undefined,进行递增运算之后undefined++就等于NaN。

为了解决这个问题,可以使用bind方法,将keith对象里的this绑定到keith对象上,或者是直接调用。

var f = keith.count.bind(keith);
f(); //1
f(); //2
f(); //3
keith.count.bind(keith)() //1
keith.count.bind(keith)() //2
keith.count.bind(keith)() //3

   

 当然,this也可以绑定到其他对象上。

var obj = {
a: 100
};
var f = keith.count.bind(obj);
f(); //100
f(); //101
f(); //102

同样,我们也可以给bind方法传递参数,第一个参数如果为null或者undefined或者this,会将函数内部的this对象指向全局环境;第二个为调用时需要的参数,并且传递参数的形式与call方法相同。

function keith(a, b) {
return a + b;
}
console.log(keith.apply(null,[1,4])); //5
console.log(keith.call(null,1,4)); //5
console.log(keith.bind(null, 1, 4)); //keith()
console.log(keith.bind(null, 1, 4)()); //5

上面代码中,可以看出call,apply,bind三者的区别:call和apply方法都是在调用之后立即执行的。而bind调用之后是返回原函数,需要再调用一次才行,有点像闭包的味道,如果对闭包概念不熟悉,可以浏览这两篇文章:深入理解javascript函数参数与闭包,浅谈JavaScript的闭包函数。

5.绑定回调函数的对象

在这篇文章javascript中this关键字详解中,有谈及到如果在回掉函数中使用this对象,那么this对象是会指向DOM对象,也就是button对象。如果要解决回调函数中this指向问题,可以用如下方法。

var o = {
 f: function() {
 console.log(this === o);
 }
 }
 $('#button').on('click', function() {
 o.f.apply(o);
 //或者 o.f.call(o);
 //或者 o.f.bind(o)();
 });

点击按钮以后,控制台将会显示true。由于apply方法(或者call方法)不仅绑定函数执行时所在的对象,还会立即执行函数(而bind方法不会立即执行,注意区别),因此不得不把绑定语句写在一个函数体内。

6.call,apply,bind方法的联系和区别

  其实用于指定函数内部的this指向的问题,这三个方法都差不多,只是存在形式上的差别。读者可以将以上的例子用三种方法尝试用三种方法实现。

  总结一下call,apply,bind方法:

  a:第一个参数都是指定函数内部中this的指向(函数执行时所在的作用域),然后根据指定的作用域,调用该函数。

  b:都可以在函数调用时传递参数。call,bind方法需要直接传入,而apply方法需要以数组的形式传入。

  c:call,apply方法是在调用之后立即执行函数,而bind方法没有立即执行,需要将函数再执行一遍。有点闭包的味道。

  d:改变this对象的指向问题不仅有call,apply,bind方法,也可以使用that变量来固定this的指向。如有疑问,请访问 javascript中this关键字详解


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn