Javascript之call bind apply

首先说一下什么是this指向?this又指向谁?

this是Js的一个关键字,随着函数的使用场合不同,this的指向也会发生相应的变化。总结来说就是谁调用this就指向谁

各个情况下this会指向谁?

1.以函数形式调用时,this永远指向window

function fun() {
    console.log(this); // window
}

2.以方法形式调用时,this指向调用方法的对象

function fun() {
    let obj = {
        name: 'ysj',
        getName() {
            console.log(this); // obj
            console.log(this.name); // ysj
        }
    };
    obj.getName();
}

3.以构造函数形式调用时,this指向新创建的那个对象

function fun() {
    this.name = 'ysj';
    this.age = 23;
}

function runFun() {
    let newFun = new fun();
    console.log(newFun.name); // ysj
}

4.以箭头函数形式调用时,this看外层是否有函数,如果有,外层函数的this就是内部箭头函数的this,如果没有那就指向window

function fun() {
    let funIn = () => {
        console.log(this); // window
    }
    funIn();
}

5.以定时器形式调用时,this指向window

function fun() {
    setTimeout(function () {
        console.log(this); // window
    })
}

更改this指向

定义:call()、apply()、bind()这三个方法都是是用来改变this的指向的

三者区别:

  • call使用:函数名字.call(对象,参数1,参数2,...);  // 立即执行,依次接收参数
  • apply使用:函数名字.apply(对象,[参数1,参数2,...]); // 立即执行,接收一个参数数组
  • bind使用:调用的时候执行,可以依次传入参数,也可以使用时传入参数
function fun() {
    function Person(a, b) {
        console.log(this);
        return a + b;
    }
    Person(1, 2); // window 3

======================================================================================================================================================

    function Student(name) {
        this.name = name;
    }
    function sayHi(textSay, endText) {
        console.log(textSay + this.name + endText);
    }
    let stu1 = new Student('张三');
    let sayHi1 = sayHi.call(stu1, '欢迎', '哈哈哈');
    let sayHi2 = sayHi.apply(stu1, ['welcome', '呵呵呵']);
    let sayHi3 = sayHi.bind(stu1, '我是bind');
    console.log(sayHi1); // 欢迎张三哈哈哈
    console.log(sayHi2); // welcome张三呵呵呵
    sayHi3(); // bind必须去调用才会执行 打印出 我是bind张三undefined
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值