JavaScript中函数可以通过3种方法改变自己的this指向,它们是call、apply、bind。它们3个非常相似,但是也有区别。下面表格可以很直观看出三者的不同
| 方法 | 是否直接执行函数 | 传入的参数 | 调用方式 |
| call | 是 |
(context,arg1,arg2,arg3...) 第二个参数之后都是实参 |
function.call(context,arg1,arg2,arg3...) |
| apply | 是 |
(context,[arg1,arg2,arg3...]) 第二个参数必须是数组 |
function.apply(context,[arg1,arg2,arg3...]) |
| bind | 否 |
(context) 只有一个参数 |
var newFunction = function.bind(context); newFunction(arg1,arg2,arg3...) |
1、call
|
1
|
var a = {x: 1}; var b = function (y, z) { console.log(this.x + y + z) }; b.call(a, 3, 4);//此时b的this(即b执行时的上下文)被改变为a,因此this.x为1,第二个参数之后都是传给b实参。 |
2、apply
|
1
|
var a = {x: 1}; var b = function (arr) { console.log(this.x + arr[0] + arr[1]) }; b.call(a, [3, 4]);//此时b的this(即b执行时的上下文)被改变为a,第二个参数是一个数组 |
3、bind
|
1
|
var a = {x: 1}; var b = function (y, z) { console.log(this.x + y + z) }; var newB = b.bind(a);//此时b的this(即b执行时的上下文)被改变为a,由此生成一个新函数,函数不会立即执行。 newB(3, 4);//函数此时才执行 |
1、数组之间追加
|
1
|
var array1 = [12, "foo", {name: "Joe"}, -2458]; var array2 = ["Doe", 555, 100]; Array.prototype.push.apply(array1, array2); /* array1 值变为 [12 , "foo" , {name:"Joe"} , -2458 , "Doe" , 555 , 100] */ View Code |
2、获取数组中的最大值和最小值
|
1
|
var numbers = [5, 458, 120, -215]; var maxInNumbers = Math.max.apply(Math, numbers); //458 View Code |
3、验证是否是数组(前提是toString()方法没有被重写过)
|
1
|
function isArray(obj){ return Object.prototype.toString.call(obj) === ‘[object Array]‘; } View Code |
4、类(伪)数组使用数组方法
|
1
|
var domNodes = Array.prototype.slice.call(document.getElementsByTagName("*")); View Code |
5、数字求和
|
1
|
function sum() { var numberSum = Array.prototype.reduce.apply(arguments, [function (prev, next) { return prev + next; }]); console.log(numberSum); } sum(1, 2, 3); |
原文:http://www.cnblogs.com/EnSnail/p/6687491.html