【前端学习笔记】call、apply、bind方法
1.call()方法:
// move函数实现移动平面图上一个点位置功能
var move = function(x,y){
this.x += x;
this.y += y;
}
// 定一个点p
var p = {x:1, y:1};
// 调用call 方法,此时p点直接会移动。
move.call(p,1,2);
console.log(p); // --> {x:2,y:3}
2.apply()方法:
// move函数实现移动平面图上一个点位置功能
var move = function(x,y){
this.x += x;
this.y += y;
}
// 定一个点p
var p = {x:1, y:1};
// 调用apply方法,此时p点直接会移动。
move.apply(p,[1,2]);
console.log(p); // --> {x:2,y:3}
3.bind()方法:
/** 函数作为返回值--bind **/
// move函数实现移动平面图上一个点位置功能
var move = function(x,y){
this.x += x;
this.y += y;
}
// // // 定一个点p
var p = {x:1, y:1};
// // bind方法收受一个参数,并返回一个接受余下参数的函数过程。此时p点并没有移动。
var pmove0 = move.bind(p);
console.log(p); // --> {x:1,y:1}
// // 这时p移动到了(2,3)位置。
pmove0(1,2);
console.log(p); // --> --> {x:2,y:3}
// 当然你也可以这样调用 var pmove1 = move.bind(p,1); console.log(p); pmove1(2); console.log(p);
// 或者这样调用 var pmove2 = move.bind(p,1,2); console.log(p); pmove2(); console.log(p);
//bind()兼容写法
if (!Function.prototype.bind) { //如果原型上没有bind方法
Function.prototype.bind = function (context) {
var args = arguments, //获取要传入的所有参数
obj = arguments[0], //获取要绑定的上下文
func = this; //获取要调用的函数
return function(){ //返回一个新的函数
var argc = Array.prototype.slice.call(args,1); //获取bind的剩余传入参数
Array.prototype.push.apply(argc,arguments); //将调用时的参数放到最后
return func.apply(obj,argc); //使用新的this执行func函数
}
}
}
4.call()、apply()方法改变this指向
//例子调用apply()方法,call()方法相同
function test(){
console.log('I am test');
}
var obj ={
move:function(x,y){
console.log(x);
console.log(y);
console.log(this); // --> obj{move:function(){}}
}
}
obj.move(44,55);
// 调用apply方法
obj.move.apply(test,[66,88]); // --> function test(){ console.log('I am test') ;}
5.bind()方法改变this指向
//调用bind()方法
function test(){
console.log('I am test');
}
var obj ={
move:function(x,y){
console.log(x);
console.log(y);
console.log(this);
}
}
obj.move(44,55);// this --> obj{move:function(){}}
var testMove = obj.move.bind(test);
testMove(66,88); // this --> function test(){ console.log('I am test'); };

浙公网安备 33010602011771号