JS中的call、apply、bind方法
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
function Animal(name){
this.name=name;
this.showName=function(){
console.log(this.name);
}
}
function Dog(name){
Animal.call(this,name);
}
var dog=new Dog("Crazy dog");
dog.showName();
输出:Crazy dog
function class1(args1,args2){
this.name=function(){
console.log(args,args);
}
}
function class2(){
var args1="1";
var args2="2";
class1.call(this,args1,args2);
/*或*/
class1.apply(this,[args1,args2]);
}
var c=new class2();
c.name();
输出:1 2
var bar=function(){
console.log(this.x);
}
var foo={
x:3
}
bar();
bar.bind(foo)();
/*或*/
var func=bar.bind(foo);
func();
输出:
undefined
3