常用的改变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值和初始化参数改造的原函数拷贝;