call()、apply()、bind()都是Function的prototype中的方法,只有函数才能调用,相应的方法参数如下:
function.call(thisArg, arg1, arg2, ...)
function.apply(thisArg, [argsArray])
function.bind(thisArg[, arg1[, arg2[, ...]]])
主要区别有两个:
1)、call()
方法、bind()
方法接受的是参数列表,而apply()
方法接受的是一个参数数组;
2)、apply()
、call()
是立即执行函数,bind()
是返回对应函数,需要再次调用才能执行。
用法有两种:
一、改变this指针的指向:
1)、改变函数作用域:
var name = "小白";
var obj = {
name: "小红"
};
function sayName() {
return this.name;
}
console.log(sayName.call(this)); //小白
console.log(sayName.call(obj)); //小红
2)、实现继承
//实现js继承
//父类
function Person(name, height) {
this.sayInfo = function() {
return "姓名:" + name + ", 身高:" + height + ", 体重:" + this.weight;
}
}
//子类
function Chinese(name, height, weight) {
Person.call(this, name, height);
this.weight = weight;
this.nation = function() {
console.log("我是中国人");
}
}
//子类
function America(name, height, weight) {
Person.apply(this, [name, height]);
this.weight = weight;
}
let chiness = new Chinese("成龙", "178cm", "60kg");
console.log(chiness.sayInfo()); //姓名:成龙, 身高:178cm, 体重:60kg
let america = new America("jack", "180cm", "55kg");
console.log(america.sayInfo()); //姓名:jack, 身高:180cm, 体重:55kg
3)、React中使用bind使函数可以获取到props
class MyCircle extends Component {
constructor(props) {
super(props)
this.func = this.func.bind(this)
}
func() {
...
}
...
}
二、数组操作:
1)、判断对象类型
var arr1 = [];
console.log(Object.prototype.toString.call(arr1)); // [object Array]
console.log(arr1.toString()); // 空
function isArray(obj) {
return Object.prototype.toString.call(obj) === '[object Array]'
}
isArray([1]) // true
isArray({}) // false
2)、找出数组中最大或者最小的元素
var arr2 = [10, 2, 5, 28, 9];
Math.max.apply(Math, arr2); // 28
Math.min.apply(null, arr2) // 2
var arr = [1, 2, 3, 4]
//取最大值
console.log(Math.max.apply(Math, arr)) // 4
console.log(Math.max.call(Math, ...arr)) // 4
//取最小值
console.log(Math.min.apply(Math, arr)) // 1
console.log(Math.min.call(Math, ...arr)) // 1
3)、将伪数组转为真正的数组
Array.prototype.slice.apply({0: 1, length: 1}); // [1]
Array.prototype.slice.apply({0: 1, length: 2}); // [1, undefined]
参考文章