在Javascript 中,call、apply 和bind 是Function对象自带的三个方法,这个三个方法主要作用是改变函数中的this指向。
apply
、 call
、bind
三者都是用来改变函数的this对象的指向的;apply
、 call
、bind
三者第一个参数都是this要指向的对象,也就是想指定的上下文(函数的每次调用都会拥有一个特殊值——本次调用的上下文(context)——这就是this
关键字的值。);apply
、 call
、bind
三者都可以利用后续参数传参;bind
是返回对应函数,便于稍后调用;apply
、call
则是立即调用
call();
语法:call([thisObj[,arg1[, arg2[, [,.argN]]]]])
定义:调用一个对象的一个方法,以另一个对象替换当前对象
说明:call方法可以用来代替另一个对象调用一个方法
call方法可将一个函数的对象上下文从初始的上下文改变为由 thisObj指定的新对象
thisObj
的取值有以下4种情况:
(1) 不传,或者传null,undefined, 函数中的this指向window对象
(2) 传递另一个函数的函数名,函数中的this指向这个函数的引用
(3) 传递字符串、数值或布尔类型等基础类型,函数中的this指向其对应的包装对象,如 String、Number、Boolean
(4) 传递一个对象,函数中的this指向这个对象
function a(){
console.log(this); //输出函数a中的this对象
}
function b(){}
var c={name:"call"}; //定义对象c
a.call(); //window
a.call(null); //window
a.call(undefined); //window
a.call(1); //Number
a.call(''); //String
a.call(true); //Boolean
a.call(b); //function b(){}
a.call(c); //Object
function class1(){
this.name=function(){
console.log("我是class1内的方法");
}
}
function class2(){
class1.call(this); //此行代码执行后,当前的this指向了class1(也可以说class2继承了class1)
}
var f=new class2();
f.name(); //调用的是class1内的方法,将class1的name方法交给class2使用
例子:
function eat(x,y){
console.log(x+y);
}
function drink(x,y){
console.log(x-y);
}
eat.call(drink,3,2) //5
function Animal(){
this.name="animal";
this.showName=function(){
console.log(this.name);
}
}
function Dog(){
this.name="dog";
}
var animal=new Animal();
var dog=new Dog();
animal.showName.call(dog);
输出:dog