JavaScript中每个Function对象都有一个 call 方法和 apply 方法,而bind会返回一个新的函数
1、call
方法调用一个函数, 其具有一个指定的this
值和分别地提供的参数(参数的列表)。
注意:该方法的作用和 apply()
方法类似,只有一个区别,就是call()
方法接受的是若干个参数的列表,而apply()
方法接受的是一个包含多个参数的数组。
function Person(name,age){
this.name = name;
this.age = age;
}
function Male(name,age,sex){
Person.call(this,name,age);
this.sex = sex;
}
var handsome = new Male('YaaLee',12,'male');
console.log(handsome.name); //'YaaLee'
2、方法调用一个具有给定 this
值的函数,以及作为一个数组(或类似数组对象)提供的参数。
注意:call()
方法的作用和 apply()
方法类似,区别就是 call()
方法接受的是参数列表,而 apply()
方法接受的是一个参数数组。
var arr = [1,5,10,20,100];
var max = Math.max.apply(null,arr);
console.log(max); //100
var min = Math.min.apply(null,arr);
console.log(min); //1
3、bind()
方法创建一个新的函数,当这个新的函数被调用时,其this
置为提供的值,其参数列表前几项,置为创建时指定的参数序列。
var module = {
x:100,
getX:function(){
return this.x;
}
}
var unboundGetX = module.getX;
console.log(unboundGetX()); //undefined
var boundGetX = unboundGetX.bind(module);
console.log(boundGetX()); //100