函数有3个方法:apply()、call()、bind()。这3个方法都会以指定的this值来调用函数,即会设置调用函数时函数体内this对象的值。apply()方法接收两个参数:函数内this的值和一个参数数组。第二个参数可以是Array的实例,但也可以是arguments对象。参考以下例子。
window.color = 'red';
let o = {
color: 'blue'
};
function productIntroduction(productName, price) {
console.log(`This product name: ${productName}, ${price} yuan, ${this.color}`);
}
a
function applyProductIntroduction(productName, price) {
productIntroduction.apply(this, arguments);
}
productIntroduction('fingerboard', 100); //This product name: fingerboard, 100 yuan, red
productIntroduction.apply(this, ['mouse', 88]); //This product name: mouse, 88 yuan, red
productIntroduction.apply(window, ['notebook', 6888]); //This product name: notebook, 6888 yuan, red
applyProductIntroduction('water cup', 48); //This product name: water cup, 48 yuan, red
productIntroduction.apply(o, ['iphone 14', 6500]); //This product name: iphone 14, 6500 yuan, blue
apply 的好处是可以将任意对象设置为任意函数的作用域,这样对象可以不用关心方法。
在使用productIntroduction.apply(o, ['iphone 14', 6500]); 把函数的执行上下文即this切换为对象o之后,结果就变成了显示"blue"了
call()方法与apply()的作用一样,只是传参的形式不同。第一个参数跟apply()一样,也是this值,而剩下的要传给被调用函数的参数则是逐个传递的。换句话说,通过call()向函数传参时,必须将参数一个一个地列出来
productIntroduction.call(o,'iphone 14', 6500); //This product name: iphone 14, 6500 yuan, blue
ECMAScript 5出于同样的目的定义了一个新方法:bind()。bind()方法会创建一个新的函数实例,其this值会被绑定到传给bind()的对象。比如:
let productBind = productIntroduction.bind(o, 'iphone 14', 6500);
console.info(typeof productBind) // function
productBind() ////This product name: iphone 14, 6500 yuan, blue
可以看到productBind 的类型为function
网友评论