深刻理解JavaScript中的this

      发布在:笔记      评论:0 条评论

this指向函数的调用者

举个例子

let pople = {
  name:"niyanan",
  age:27,
  url:niyanan.com,
  say:function(){
      console.log(`我叫${this.name},年龄${this.age},博客${this.url}`)
  }
}
//我叫niyanan,年龄27,博客niyanan.com
pople.say()
let man = pople.say

//我叫undefined,年龄undefined,博客undefined
man()

let man = pople.say并没有执行,而是把 pople.say 这个函数复制给了man,全局变量和函数中的this都指向window(let除外),man执行时 pople.say函数中的this就指向了window,但是 window 中并没有定义name、age、url属性,所以会输出undefined,稍作改造

let pople = {
  name:"niyanan",
  age:27,
  url:niyanan.com,
  say:function(){
      console.log(`我叫${this.name},年龄${this.age},博客${this.url}`)
  }
}
//我叫niyanan,年龄27,博客niyanan.com
pople.say()
let man = pople.say.bind(pople)

//我叫niyanan,年龄27,博客niyanan.com
man()

我们在pople.say添加了bind()函数,就正常输出我叫niyanan,年龄27,博客niyanan.com,这个函数的意思是将pople.say函数中的this绑定到 pople 对象上,pople一定是一个对象,在举例说明

let pople = {
  name:"niyanan",
  age:27,
  url:niyanan.com,
  say:function(){
      console.log(`我叫${this.name},年龄${this.age},博客${this.url}`)
  }
}
//我叫niyanan,年龄27,博客niyanan.com
pople.say()
let man = pople.say.bind({
  name:"nijie",
  age:38,
  url:niyanan.cn,
})

//我叫nijie,年龄38,博客niyanan.cn
man()

被调用的函数也可以传参数

let pople = {
  name:"niyanan",
  age:27,
  url:niyanan.com,
  say:function(gender){
      console.log(`我叫${this.name},${gender},年龄${this.age},博客${this.url}`)
  }
}
//我叫niyanan,男,年龄27,博客niyanan.com
pople.say('男')
let man = pople.say.bind({
  name:"nijie",
  age:38,
  url:niyanan.cn,
},'男')

//我叫nijie,男,年龄38,博客niyanan.cn
man()
Responses