leslie1943 / blog

Some front-end points and some interview questions.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

JavaScript中的this

leslie1943 opened this issue · comments

this

  • 函数真正被调用执行的时候确定 this, 定义期无法确定this
  • 严格模式下, this被禁止指向全局对象
  • 1: 全局环境中, this 指向 window this == window // true
  • 2: 构造函数中, this 指向被new出来的对象
  • 3: 对象方法中, 如果函数作用对象的方法时, 方法中的this指向该对象
const person = {
    name: 'leslie',
    say: function() {
        console.info(this.name, 'say')
    },
    talk() {
        console.info(this.name, 'talk')
    }
}
person.say() // leslie, say
  • 4: 函数call,apply 或者 bind的调用, 当一个函数被call/apply/bind调用时, this的值就是传进去的对象
  • 5: DOM event在一个HTML DOM事件处理程序中, this始终指向这个处理程序绑定的 HTML DOM节点
  • 6: 箭头函数中的this: 箭头函数完全修复了this的指向, this总是指向词法作用域, 也就是外层调用者obj, 由于this在箭头函数中已经按照词法作用域绑定了, 所以用call/apply调用箭头函数时, 无法对this进行绑定, 也就是说传入的第一个参数将被忽略.
const name = 'global name'
const say = (first, last) => {
    console.info(first,this.name, last)
}
const obj = {
    name: 'obj name'
}
say.call(obj,'one','two') // one global name two => 并未修改this的指向