apply vs call
apply
與 call
的功能一樣菩收,都是: 劫持另外一個(gè)對象的方法牌里,繼承另外一個(gè)對象的屬性,區(qū)別在于使用時(shí)傳參不同,具體如下:
// apply使用
FunctionName.apply(obj, args) 該方法接受兩個(gè)參數(shù)
obj: 這個(gè)對象將代替FunctionName類里this對象
args: 這個(gè)是數(shù)組,它將作為參數(shù)傳遞給FunctionName嚣鄙,并且傳遞過去的參數(shù)不再是數(shù)組,而是參數(shù)列表
// call使用
FunctionName.call(obj, [param1 [, param2 [, param3]]])
obj: 這個(gè)對象將代替FunctionName類里this對象
params: 這個(gè)是一個(gè)參數(shù)列表,相當(dāng)于 args = [param1 [, param2 [, param3]]]
// 舉個(gè)例子
function Person(name, age) {
this.name = name;
this.age = age;
}
function Student(name, age, grade) {
console.info('arguments:', JSON.stringify(arguments));
// arguments: {"0":"js","1":12,"2":100}
Person.apply(this, arguments);
this.grade = grade;
}
let student = new Student('js', 12, 100)
console.info('student: ', JSON.stringify(student));
// student: {"name":"js","age":12,"grade":100}
由于apply可以將一個(gè)數(shù)組解析為一個(gè)一個(gè)的參數(shù)渺蒿,那么我們在很多地方,都可以方便的使用一些函數(shù)彪薛,例如求取最大值茂装,最小值,數(shù)組拼接等等
// 求最大值
const a = [1, 2, 3];
const max = Math.max.apply(null, a); // 等價(jià)于 Math.max(1, 2, 3)
// 求最小值
const a = [1, 2, 3];
const min = Math.min.apply(null, a); // 等價(jià)于 Math.min(1, 2, 3)
// 拼接數(shù)組
const arr1 = ['a', 'b', 'c'];
const arr2 = ['d', 'e'];
const arr3 = Array.prototype.push.apply(arr1, arr2); // 等價(jià)于 arr1.push('d', 'e')