js中使用call、apply 及 bind改变this指向

首先我们引用一段代码,较为直观的展示三者的区别

    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('飞机初始化')
        }
    }
  1. 使用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()//玩家飞机移动
  1. 使用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();//敌方飞机移动
  1. 使用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"}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值