day17_call、apply和bind
1.call
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);
2.apply
const numbers = [5, 6, 2, 3, 7];
const max = Math.max.apply(null, numbers);
console.log(max); //7
- 重写apply()
var arr = [1, 2, 3, 4];
class Maths {
static max() {
if (arguments.length < 1) return;
var max = arguments[0]
for (var i = 0; i < arguments.length; i++) {
max = max > arguments[i] ? max : arguments[i];
}
return max;
}
}
var max = Maths.max.apply(null, arr);
console.log(max);
3.bind函数
var a = foo.bind();
//bind会创建一个新函数,并返回; => 复制一个一模一样的函数返回;
- 将函数中的this绑定为带入的对象,但是不执行该函数
var obj = {
arr: [1, 2, 3, 4],
num: 0,
init: function () {
var bn = document.createElement("button");
bn.textContent = "按钮";
this.clickBind = this.clickHandler.bind(this);
bn.addEventListener("click", this.clickBind);
document.body.appendChild(bn);
},
clickHandler(e) {
console.log(this);//bn
e.currentTarget.removeEventListener("click", this.clickBind);
}
}
obj.init();
function bind(fn, _this) {
var argArray = Array.from(arguments);
console.log(argArray); // [ƒ, {…}, 1, 2, 3]
argArray = argArray.slice(2);
console.log(argArray); //[1, 2, 3]
return function() {
var outerFnArgArray = Array.from(arguments);//[4, 5, 6]
console.log(outerFnArgArray);
fn.apply(_this, argArray.concat(outerFnArgArray));
}
}
function foo(a, b, c, d, e, f) {
console.log(this, a, b, c, d, e, f);//{name: "hello"} 1 2 3 4 5 6
}
var bindFn = bind(foo, {
name: "hello"
}, 1, 2, 3)
bindFn(4, 5, 6);
4.三者之间的区别
-
bind和apply、call的区别
-
apply和call的区别
function foo(a, b, c) { console.log(this, a, b, c); } foo.apply({ name: "hello" }, [1, 2, 3]); // apply 第二个参数和 arguments 相对应; foo.call({ name: "hello" }, 4, 5, 6)