call/apply/bind

使用 call() 和 apply()

call 和 apply是 Function 对象的原型方法,它们能够将特定函数当作一个方法绑定到指定对象上并进行调用。具体用法如下:

1
2
function.call(thisobj, args... ) 
function.apply(thisobj, args)

其中参数 thisobj 表示this指定的对象,参数 args 表示要传递给被调用函数的参数。 call()方法只能接收多个参数列表, 而 apply()只能接收一个数组或者伪类数组,数组元素将作为参数传递给被调用的函数。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
//定义一个add 方法
function add(x, y) {
return x + y;
}

//用call 来调用 add 方法
function myAddCall(x, y) {
//调用 add 方法 的 call 方法
return add.call(this, x, y);
}

//apply 来调用 add 方法
function myAddApply(x, y) {
//调用 add 方法 的 applly 方法
return add.apply(this, [x, y]);
}

console.log(myAddCall(10, 20)); //输出结果30

console.log(myAddApply(20, 20)); //输出结果40

使用 bind()

用来把函数绑定到指定对象上。

1
function.bind(thisArg [, arg1[, arg2 [, argN]]])

function:必需参数, 一个函数对象。 2.thisArg:必需参数,this关键字可在新函数中引用的对象。 3.arg1[, arg2[, argN]]:可选参数,要传递到新函数的参数的列表。

1
2
3
4
5
6
7
8
9
10
11
var checkNumericRange = function (value) { 
if (typeof value !== 'number'){
return false;
}else{
return value >= this.minimum && value <= this.maximum;
}
}
var range = { minimum: 10, maximum: 20 };
var boundCheckNumericRange = checkNumericRange.bind(range);
var result = boundCheckNumericRange (12);
document.write (result); //true

评论

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×