对call,apply,bind的理解

常用的改变this指向的方法有call,apply,bind:

call

call方法:调用一个对象,简单理解为调用函数的方式,但是他可以改变函数的this指向;

fun.call(thisArg, arg1, arg2, …)
thisArg:在fun函数运行时指定的this值;
arg1,arg2:传递的其他参数,返回值就是函数的返回值,因为他就是调用函数;

function  Father() {this}

function  Son() {Father.call(this,1,2)}

因此当我们想改变this指向,同时想调用这个函数的时候,可以使用call,比如继承;

apply

apply方法:
fun.apply(thisArg, [argsArray]); // 调用函数
thisArg:在fun函数运行时指定的this值;
argsArray: 传递的值,必须包含在数组里面;
返回值就是函数的返回值,因为他就是调用函数;
因此apply主要跟数组有关系,比如使用Math.max()求数组的最大值;

var obj = {name: 'zhuyilong'}
function fn(arr) {
	console.log(this);
	console.log(arr);
	console.log(arr2);
}
var arr = [23, 23, 43, 34, 32];
var n = Math.max.apply(null, arr);
console.log(n);
bind

bind方法:不会调用函数,但是能改变函数内部this指向
fun.bind(thisArg, arg1, arg2);
thisArg:在fun函数运行时指定的this值;
arg1,arg2:传递的其他参数;
返回由指定的this值和初始化参数改造的原函数拷贝;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值