一.前言
1.apply,call和bind常出现前端面试中
2.以下的一些知识总结主要来自MDN文档
3.现阶段整理的都是一些比较浅显的知识点,欢迎批评指正!
二.apply
1.作用:Function.prototype.call()
call() 方法使用一个指定的 this 值和单独给出的
一个或多个参数来调用一个函数。
2.区别:此方法的语法和作用与call()方法类似,只有一个区别,就是:
call() 方法接受的是一个参数列表,而 apply() 方法接受的是一个包含多个参数的数组。
3.代码如下:Function.apply()
function Product(name, price) {
this.name = name;
this.price = price;
}
function Food(name, price) {
Product.call(this, name, price);
this.category = 'food';
}
console.log(new Food('cheese', 5).name);
// expected output: "cheese"
4.语法
func.apply(thisArg, [argsArray])
- 参数:
thisArg 必选的。在 func 函数运行时使用的 this 值。请注意,this可能不是该方法看到的实际值:如果这个函数处于非严格模式下,则指定为 null 或 undefined 时会自动替换为指向全局对象,原始值会被包装。 argsArray 可选的。一个数组或者类数组对象,其中的数组元素将作为单独的参数传给 func 函数。如果该参数的值为 null 或 undefined,则表示不需要传入任何参数。从ECMAScript 5 开始可以使用类数组对象。 浏览器兼容性 请参阅本文底部内容。
- 返回值:
调用有指定this值和参数的函数的结果
三.call
1.作用:
call() 方法使用一个指定的 this 值和单独给出的
一个或多个参数来调用一个函数。
2.区别:
该方法的语法和作用与 apply() 方法类似,只有一个区别,就是 call() 方法接受的是一个参数列表,而 apply() 方法接受的是一个包含多个参数的数组。
3.代码:
function Product(name, price) {
this.name = name;
this.price = price;
}
function Food(name, price) {
Product.call(this, name, price);
this.category = 'food';
}
console.log(new Food('cheese', 5).name);
// expected output: "cheese"
4.语法:
function.call(thisArg, arg1, arg2, ...)
- 参数 thisArg 可选的。在 function 函数运行时使用的 this 值。请注意,this可能不是该方法看到的实际值:如果这个函数处于非严格模式下,则指定为 null 或 undefined 时会自动替换为指向全局对象,原始值会被包装。 arg1, arg2, ... 指定的参数列表。
- 返回值
使用调用者提供的 this 值和参数调用该函数的返回值。若该方法没有返回值,则返回 undefined。
四.bind
1.作用:
bind() 方法创建一个新的函数,在 bind() 被调用时,
这个新函数的 this 被指定为 bind() 的第一个参数,
而其余参数将作为新函数的参数,供调用时使用。
2.代码:
const module = {
x: 42,
getX: function() {
return this.x;
}
};
const unboundGetX = module.getX;
console.log(unboundGetX()); // The function gets invoked at the global scope
// expected output: undefined
const boundGetX = unboundGetX.bind(module);
console.log(boundGetX());
// expected output: 42
3.语法:
function.bind(thisArg[, arg1[, arg2[, ...]]])
- 参数
thisArg 调用绑定函数时作为 this 参数传递给目标函数的值。 如果使用new运算符构造绑定函数,则忽略该值。当使用 bind 在 setTimeout 中创建一个函数(作为回调提供)时,作为 thisArg 传递的任何原始值都将转换为 object。如果 bind 函数的参数列表为空,或者thisArg是null或undefined,执行作用域的 this 将被视为新函数的 thisArg。 arg1, arg2, ... 当目标函数被调用时,被预置入绑定函数的参数列表中的参数。
- 返回值
返回一个原函数的拷贝,并拥有指定的 this 值和初始参数。