JavaScript - this指向问题(建议收藏反复查看)

今天认真研究了一下关于JavaScript中this指向的问题,总结了以下规律,希望能对this指向不明白的同学一点帮助。

1.在全局环境下

this 始终指向全局对象(window), 无论是否严格模式。

console.log(this.document == document); //true
console.log(this === window); //true
this.a = 37;
console.log(window.a); //37
console.log(this)//window

2.普通函数直接调用

  • 非严格模式下 指向window
  • 严格模式下,为undefined
//非严格模式
function fun1() {
  console.log(this); //window
}
fun1();
//严格模式
function fun2() {
  "use strict";
  console.log(this); //undefined
}
fun2();

3.对象函数调用

哪个对象调用 ,则该函数最外层this就指向哪个对象。

var obj = {
   fn: function () {
   console.log(this)
   }
}
obj.fn()//obj
let obj1 = {
  a: 222,
  fn: function () {
    console.log(this.a);
  },
};
let obj2 = {
  a: 111,
  b: 333,
  fn: function () {
    console.log(this.a);
    console.log(this.b);
  },
};
obj1.fn = obj2.fn;
obj1.fn(); //222  undefined

4.构造函数的调用

构造函数的this指向新创建的那个函数,即自己。

let fun1 = function () {
  this.name = "111";
};
let fun2 = new fun1();
console.log(fun2.name); //111
let fun3 = function () {
  this.name = '111'
}
let fun4 = new fun3();
fun4.name = 'cn';
console.log(fun4.name)//cn

注意点:在构造函数里面返回一个对象,会直接返回这个对象,而不是执行构造函数后创建的对象

let fun5 = function () {
  this.name = 'huanan'
  this.age = 10;
  return { name: '111' }
}
var fun6 = new fun5()
console.log(fun6.name)//111
console.log(fun6.age)//undefined
let fun7 = function () {
  this.name = "huanan";
  this.age = 10;
  return 111;
};
var fun8 = new fun7();
console.log(fun8.name); //huanan
console.log(fun8.age); //10

5.箭头函数

箭头函数没有this,箭头函数的this永远指向自己外面的一层。如果上一层是箭头函数,则再向外寻找一层。

obj3 = {
  fn: function () {
    console.log(this); //obj1
    setTimeout(() => {
      console.log(this); //obj1
    });
  },
};
obj3.fn();
let obj4 = {
  fn: () => {
    console.log(this); //window
    setTimeout(() => {
      console.log(this); //window
    });
  },
};
obj4.fn();
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值