扩充函数作用域
简介
apply()和call()是每个函数所包含的方法,用于指定函数运行的作用域(修改this对象的值);bind()用于绑定函数运行作用域并返回函数
用法
apply()
apply()接收两个参数,第一个参数指定函数运行时的作用域,第二个参数指定函数的参数(需是数组或者arguments对象)
example1:参数传递
function sum(num1, num2) {
return num1 + num2;
}
function callSum1(num1, num2) {
return sum.apply(this, arguments);//传入arguments对象
}
function callSum2(num1, num2) {
return sum.apply(this, [num1, num2]);//传入数组
}
example2:修改作用域
var name = "first";
var obj = {name: "second"};
function getName() {
console.log(this.name);
}
getName();//当前作用域window:"first"
getName.apply(this);//指定作用域为window:"first"
getName.apply(obj);//指定作用域为obj:"second"
call()
call()接收多个参数,第一个参数与apply一致,其余参数为函数需要的参数(需一一列举)
example:参数传递
function sum(num1, num2) {
return num1 + num2;
}
function callSum(num1, num2) {
return sum.call(this, num1, num2);//指定每一个参数
}
bind()
bind()方法接收一个参数,参数指定函数运行时的作用域
example:
var name = "first";
var obj = {name: "second"};
function getName() {
console.log(this.name);
}
var newGetName = getName.bind(obj);
getName();//"first"
newGetName();//绑定作用域为obj:"second"