首页 > 其他 > 详细

this的指向

时间:2021-08-21 22:44:41      阅读:37      评论:0      收藏:0      [点我收藏+]

this指向

常规函数

概念:this的指向只跟两个条件有关,

  • 调用函数的位置
  • 调用函数的方式

常规函数包含

  • 普通函数
  • 匿名函数
  • 立即执行函数

箭头函数

概念:箭头函数本身没有this,所以写在箭头函数中的this,指向包裹箭头函数的函数。

换而言之,箭头函数的this只跟箭头函数声明的位置有关,和调用者无关

function fn1(){
    return ()=>{
        console.log(this)
    }
}
const obj = {
    a:()=> {
      	console.log(this)
    }
}
fn1()()//this指向fn1
obj.a()//this指向window,因为包裹着a这个箭头函数的函数没有,所以指向了window,对象是没有作用域的

输出一下程序中的打印结果

const obj = {
  dev: ‘bfe‘,
  a: function() {
    return this.dev
  },
  b() {
    return this.dev
  },
  c: () => {
    return this.dev
  },
  d: function() {
    return (() => {
      return this.dev
    })()
  }
}

console.log(obj.a())
console.log(obj.b())
console.log(obj.c())
console.log(obj.d())

答案:自己运行程序看结果

解析

const obj = {
  dev: ‘bfe‘,
  a: function() {
    return this.dev
  },
  b() {
    return this.dev
  },
  c: () => {
    return this.dev
  },
  d: function() {
    return (() => {
      return this.dev
    })()
  }
}

console.log(obj.a())
//obj.a(),a的调用者是obj,所以,a指向obj,this=obj,
console.log(obj.b())
//同上
console.log(obj.c())
//箭头函数,this指向只跟声明函数的位置有关,指向包裹他的函数,这里指向window
console.log(obj.d())
//这里()(),是立即执行函数,他的this指向调用者obj

this的指向

原文:https://www.cnblogs.com/letgofishing/p/15170718.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!