1. apply的使用
a. 参数类型:
第一个参数是this要指向的对象; 第二个参数是数组;
如果一个参数都不传递, this默认指向window;
b. 调用方式:
会直接执行函数;
const apply_obj = {
name: 'apply',
}
function func_apply(x,y,z) {
console.log(this,x,y,z);
}
func_apply.apply(apply_obj, ['x', 'y', 'z']);
// 输出结果 {name: 'apply'} 'x' 'y' 'z'
func_apply.apply(apply_obj, 'x', 'y', 'z');
// 会直接报错 Uncaught TypeError: CreateListFromArrayLike called on non-object
2. call的使用
a. 参数类型:
第一个参数是this要指向的对象; 后面是参数列表,可以传入任意类型,任意个数;
如果一个参数都不传递, this默认指向window;
b. 调用方式:
会直接执行函数;
const callObj = {
name: 'callObj'
};
function func_call(params1, params2, params3, params4, params5, params6,) {
console.log(this, params1, params2, params3, params4, params5, params6);
}
func_call.call(callObj, 'real_params', 'real_params2', ['a0','b'], null, undefined, {});
// 输出结果: {name: 'callObj'} 'real_params' 'real_params2' ['a0', 'b'] null undefined {}
func_call.call();
//输出结果: window{...}
3. bind的使用
a. 参数类型:
第一个参数是this要指向的对象; 第二个参数为数组, 作为实参传递; 传入多余或者其他形式的参数 会显示为undefined
如果一个参数都不传递, this默认指向window;
b. 调用方式:
调用了bind方法会后会返回一个新的执行函数,需要再次调用;
const bind_obj = {
name: 'bind',
};
function test(params,a,b) {
console.log(this);
console.log(params,a,b);
}
const testObj = test.bind(bind_obj, ['a','b'],'b');
testObj();
// 输出结果:
// {name: 'bind'}
// ['a', 'b'] 'b' undefined
4. 总结
相同点:
1 三者都可以用于改变this的指向;
2 三种方式的第一个参数都是表示需要改变的this指向;如果没有传递, 默认指向window;
不同点:
1 apply 和 call 改变this指向之后, 会直接调用; bind返回的是一个新的函数, 需要再次调用;
2 apply和bind的第二个参数都是数组, call可以传递多个参数;
5. 使用
- 通过call来封装函数判断数据类型;
function getDataType(data) {
// 获取当前数据类型;
const objType = Object.prototype.toString.call(data);
let sub = objType.substr(8);
const length = sub.length;
sub = sub.substr(0, length - 1);
// 转换成小写
const dataType = sub.toLowerCase(sub);
return res;
}