call、apply、bind
call、apply、bind的作用相同,都是改变函数运行时的this指向(this的指向问题可参考——this关键词)。
call
call()
方法通过指定的this
值和单独给出的一个或多个参数来调用一个函数。
function.call(thisArg, arg1, arg2, ...)
-
thisArg
:可选,表示function
函数调用时的this
的值。值为null
或undefined
时,this
指向全局对象。 -
arg1, arg2, ...
:参数列表。
实例代码:
//应用一:继承
function Product(name, price) {
this.name = name;
this.price = price;
}
function Food(name, price) {
Product.call(this, name, price);
this.category = 'food';
}
function Toy(name, price) {
Product.call(this, name, price);
this.category = 'toy';
}
var cheese = new Food('feta', 5);
var fun = new Toy('robot', 40);
//应用二:调用匿名函数
var animals = [
{ species: 'Lion', name: 'King' },
{ species: 'Whale', name: 'Fail' }
];
for (var i = 0; i < animals.length; i++) {
(function(i) {
this.print = function() {
console.log('#' + i + ' ' + this.species
+ ': ' + this.name);
}
this.print();
}).call(animals[i], i);
}
apply
apply()
方法调用一个具有给定this
值的函数,以及作为一个数组或类数组提供的参数。
function.apply(thisArg, [argsArray])
-
thisArg
:必选,表示function
函数调用时的this
的值。值为null
或undefined
时,this
指向全局对象。 -
argsArray
:可选,一个数组或类数组对象,其中的元素作为单独参数传给function
函数。如果值为null
或undefined
,则表示不需要传入任何参数。
实例代码:
//应用一:继承
function Person(name,age){ //定义一个类,人类
this.name=name; //名字
this.age=age; //年龄
this.sayhello=function(){alert("hello")};
}
function Print(){ //显示类的属性
this.funcName="Print";
this.show=function(){
var msg=[];
for(var key in this){
if(typeof(this[key])!="function"){
msg.push([key,":",this[key]].join(""));
}
}
alert(msg.join(" "));
};
}
function Student(name,age,grade,school){ //学生类
Person.apply(this,arguments);
this.grade=grade; //年级
this.school=school; //学校
}
var p1=new Person("jake",10);
p1.sayhello();
var s1=new Student("tom",13,6,"清华小学");
s1.show();
s1.sayhello();
alert(s1.funcName);
//应用二:令数组能够使用Number对象的方法
function getMax2(arr){
return Math.max.apply(null,arr);
}
bind
bind()
方法创建一个新的函数,在bind()
被调用时,这个新函数的this
被指定为bind()
的第一个参数,而其余参数将作为新函数的参数,供调用时使用。
function.bind(thisArg, arg1, arg2, ...)
-
thisArg
:调用绑定函数时作为this
参数传递给目标的函数的值。 -
arg1, arg2, ...
:当目标函数被调用时,被预置入绑定函数的参数列表中的参数。
比较
call | apply | bind | |
---|---|---|---|
作用 | 改变函数运行时的this 指向 |
改变函数运行时的this 指向 |
改变函数运行时的this 指向 |
第一个参数 |
this ,代表调用此函数的对象 |
this ,代表调用此函数的对象 |
this ,代表绑定此函数的对象 |
剩余参数 | 一个或多个参数 | 数组或类数组对象 | 一个或多个参数 |
使用结果 | 直接调用函数 | 直接调用函数 | 相当于声明一个新函数 |
返回值 | 返回调用该函数所返回的值 | 返回调用该函数所返回的值 | 返回一个改变了上下文this 后的函数
|
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。