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

组件中定义的函数this是什么?通过bind和箭头函数怎么添加到类的实例对象上并直接使用 #33

Open
guowei55555 opened this issue Jun 1, 2021 · 1 comment

Comments

@guowei55555
Copy link

No description provided.

@sdkll
Copy link

sdkll commented Jun 3, 2021

绑定this主要有2种方式

1.箭头函数

  • 箭头函数自身不绑定this

1

  • 自定义函数的this是谁调用就指向谁,所以onIncrement中的this就指向下方红色的this,而红色的this指向外部render(),render()中的this就是我们需要的组件实例,可以获取到setState()

2.bind()

  • 利用ES5中的bind()方法,将事件处理程序中的this与组件实例绑定到一起

2

  • 通过bind()绑定后,函数不论以何种形式调用,其this指向都不会再发生改变,只指向我们绑定好的this

@Dogtiti Dogtiti removed the Cbayel label May 11, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

3 participants