前端之JS-this的几种情况

this指向问题分为不同的情况,万变不离其宗,一般来讲谁调用this,this就指向谁。

普通对象函数中的this

var apple = 'one';
var obj = {
    apple: 'two',
    prop: {
    apple: 'three',
    getNum: function() {
        console.log(this.apple);
      }
    }
 }
 console.log(obj.prop.getNum()) // three
 var test = obj.prop.getNum;
 test(); //这里test是在函数体外定义的,默认由全局this调用,所以输出one

全局this和局部this

当在全局定义了this.var时,函数里面再用this实际上是改变了全局this的值,赋值到this
在这里插入图片描述

构造函数this

function f() {
    console.log(this);
}
f(); // window
var ff = new f(); // 这一步执行的构造函数方法里面this指向f而非window

匿名函数的this:匿名函数的this具有全局性

var obj = {
    say: function() {
        console.log(this); // {say: function}
        setTimeout(function() {
        console.log(this); // window
        })
    (function() {
       console.log(this); // window
    })();
   }
} 
obj.say();

严格模式下的this

function() {
    'use strict';
    console.log(this); // undefined
 }
 test();

普通函数的this和箭头函数的this比较

普通函数的this指向执行时的对象(即谁调用就指向谁);
箭头函数的this指向定义所在的对象

// 普通函数的this
var normal = {
        a: 1,
        b: 2,
        say: function() {
            console.log(this.a + this.b); // 3
        }
    }
normal.say();

// 箭头函数
var normal = {
        a: 1,
        b: 2,
        say: () => {
            console.log(this.a + this.b); // NaN,此时没有定义this
        }
    }
normal.say();

// setTimeout中的箭头函数,同样指向定义它的值
var obj = {
    say: function() {
        setTimeout(() => {
            console.log(this); // {say: function}
        })
     }
}
obj.say(); // 注意这里的setTimeout中的this指向的是父级中定义好的say函数,与匿名函数区分一下,匿名函数指向window


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值