首先我们引用一段代码,较为直观的展示三者的区别
function allPlane(src,x,y,speed,blood) {//所有的飞机模板
this.src = src;
this.x = x;
this.y = y;
this.speed = speed;
this.blood = blood;
this.move = function () {
console.log('移动')
};
this.init = function () {
console.log('飞机初始化')
}
}
- 使用apply
function playPlane(src,x,y,speed,blood) {//玩家飞机构造函数
console.log(this);//this为playPlane构造函数的实例化对象(play1)
allPlane.apply(this,arguments);//两个参数,第一个仍是this指向,第二个为数组,arguments的参数一一对应
this.move = function () {//重写了move方法,多态
console.log('玩家飞机移动')
}
}
let play1 = new playPlane('/img',20,20,10,100);
play1.move()//玩家飞机移动
- 使用call
function enemyPlane(src,x,y,speed,blood){
console.log(this);//this为enemyPlane构造函数的实例化对象(play2)
allPlane.call(this,src,x,y,speed,blood);//实例化对象(play2)去继承allPlane构造函数的属性和方法
this.move = function () {
console.log('敌方飞机移动')
}
}
let play2 = new enemyPlane('/img',12,45,100,10);//实例化敌方飞机
play2.move();//敌方飞机移动
- 使用bind
function myPlane(src,x,y,speed,blood){
console.log(this);//this为myPlane构造函数的实例化对象(play3)
allPlane.bind(this,src,x,y,speed,blood);//实例化对象(play3)去继承allPlane构造函数的属性和方法
this.move = function () {
console.log('我方飞机移动')
}
}
let play3 = new myPlane('/img',12,45,100,10);//实例化敌方飞机
play3.move();//我方飞机移动
拓展bind的其他用法
function text() {
this.name = 'abc';
}
function text2() {
text.bind(this)();
this.age = '18';
}
let a = new text2();
console.log(a);//text2 {name: "abc", age: "18"}