js中的this指向

一.普通函数

方法是谁调用的,this就指向谁,如果没有元素调用,那么this会指向window

    {//有元素调用函数
        let obj = {
            name: "obj",
            fn: function () {
                console.log(this);//obj
            }
        };
        obj.fn();
    }

    {//没有元素调用函数
        function fn() {
            console.log(this);//window
        }
        fn();
    }

二.构造函数

构造函数中的this指向实例本身

        function Fn(name){
            this.name = name;
            this.age = 18;
            console.log("Fn中的this==>",this); //new Fn()
        }
        Fn.prototype.sayName = function(){
            console.log(this.name); 
            console.log(this)
        }

        let fn = new Fn("哈哈");
        fn.sayName() //哈哈  Fn {name: '哈哈', age: 18}
        console.log(fn); //Fn {name: '哈哈', age: 18}

三.对象函数

在对象函数中调用,this就是当前对象

window.b=2222
let obj={
    a:111,
    fn:function(){
        alert(this.a);//111
        alert(this.b);//undefined
    }
}
obj.fn();

四.构造函数

构造函数中的this指向实例本身(实例化出来的对象)

        function Fn(name) {
          this.name = name;
          this.age = 18;
          console.log("Fn中的this==>", this); //new Fn()
        }
        Fn.prototype.sayName = function () {
          console.log(this.name); //new Fn()
          console.log("sayName中的this==>", this);
        };

        let fn = new Fn("哈哈");
        fn.sayName();
        console.log(fn);

五.箭头函数

箭头函数中的this指向箭头函数父级的上下文

        let obj = {
          name: "obj",
          fn: function () {
            console.log(this); //obj
            let fn2 = () => {
              console.log("箭头函数 fn2 中的this指向=========>", this); //obj
            };
            fn2();
          },
        };
        obj.fn();

六.call,apply和bind

如果用call、apply、bind调用函数,这三个函数的第一个参数就是this指向,但是这三个参数不能改变箭头函数的this指向

  • call(arg, arg2, args, ...)

    • 第一个参数:this指向

    • call方法从第二个参数起是一个参数列表

    • 原函数立即执行

  • apply(arg, arg2)

    • 第一个参数:this指向

    • 第二个参数:数组或者伪数组

    • 原函数立即执行

  • bind(arg, args2)

    • 第一个参数:this指向

    • 第二个参数:数组或者伪数组,可以分多次传参

    • 返回的是一个函数,原函数不立即执行

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值