this指向

this指向调用函数的对象

this一定指向一个对象(面向对象:函数一定是被某个对象调用)

1.全局作用域下,this始终指向window对象。

        

console.log(this);//window

2.函数内部的this,在非严格模式下,指向window对象:

aa()
function aa(){
    bb()
    console.log(this)//window
    function bb(){
         console.log(this)//window
    }
}

3.函数内部的this,在严格模式下:

    aa();
    window.aa();

    function aa() {
      'use strict'
      console.log(this);
    }
//使用aa()调用时,this是undefined,使用window.aa()调用时,指向window

4.对象中的this,谁调用就指向谁

    const obj = {
      fn: function () {
        console.log(this)
      },
      abc: {
        fn: function () {
          console.log(this)
        }
      }
    }
    obj.fn();//obj
    obj.abc.fn();//obj.abc

/*
    如果对象b继承对象a:
*/
	const a = {
        fn:function(){
            console.log(this)
        }
    }
    const b = Object.create(a);
	b.fn();//this指向b
	a.fn();//this指向a

5.箭头函数中的this

箭头函数中没有this和arguments。

它会捕获自己定义所处的外层执行环境,并且继承这个this值,指向当前定义时所在的对象。箭头函数的this指向在被定义的时候就确定了, 之后永远都不会被改变,即使使用call apply() bind()等方法改变this指向也不可以

    const obj = {
      abc: {
        fn: () => {
          console.log(this)
        }
      }
    }
    obj.abc.fn();
因为obj在window作用域下,所以箭头函数的this指向window。

6.构造函数中的this:

构造函数在生成对象时,this指向生成的对象实例。没有生成前,函数的this没有确定指向

	function fn() {
      this.a = 123;
      this.b = function () {
        console.log(this);
      }
    }
    let abc = new fn();
    abc.b();

7.原型链中的this:

指向它调用它的对象,而不是从原型链上找他它时,它所属于的对象。

    const father = {
      a: function () {
        console.log(this)
      }
    }

    const son = { b: 2 };

    Object.setPrototypeOf(son, father)

	father.a()//father
    son.a()//son

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值