Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

JavaScript中的this #14

Open
leslie1943 opened this issue Nov 19, 2020 · 0 comments
Open

JavaScript中的this #14

leslie1943 opened this issue Nov 19, 2020 · 0 comments
Labels
documentation Improvements or additions to documentation

Comments

@leslie1943
Copy link
Owner

leslie1943 commented Nov 19, 2020

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的指向
@leslie1943 leslie1943 added the documentation Improvements or additions to documentation label Nov 19, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
documentation Improvements or additions to documentation
Projects
None yet
Development

No branches or pull requests

1 participant