-
Notifications
You must be signed in to change notification settings - Fork 384
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
在react中使用箭头函数引发的对this的思考 #14
Comments
可能的三种方案
|
@cagen thanks! |
@youngwind 谢谢你提出的问题 class Header extends React.Component {
handleClick = (e) => {
console.log(e);
}
render() {
return (
<div>
<button type="button" onClick={this.handleClick}>点击</button>
</div>
)
}
} 具体使用方法,可以到Babel官网查看 |
var demo2 = { |
test1 依然是demo2的属性,但是调用时箭头函数里的this指向的是全局对象。 |
箭头函数的this指向他所在作用域的this,这个箭头函数所在的作用域是全局作用域,所以this指向window。注意,js只有全局作用域和函数作用域
…---原始邮件---
发件人: "RuinousCheng"<notifications@github.com>
发送时间: 2019年9月28日 19:39:44
收件人: "youngwind/blog"<blog@noreply.github.com>;
抄送: "Subscribed"<subscribed@noreply.github.com>;
主题: Re: [youngwind/blog] 在react中使用箭头函数引发的对this的思考 (#14)
var demo2 = {
x : 1,
test1 : () => { console.log(this.x); },
test2 : function() {
this.test1();
}
};
这个test1怎么是定义在全局的,这不是再demo2里面定义的吗
test1 依然是demo2的属性,但是调用时箭头函数里的this指向的是全局对象。
—
You are receiving this because you are subscribed to this thread.
Reply to this email directly, view it on GitHub, or mute the thread.
|
前言
用es6一段时间了,某次想把组件内部的函数都改写成箭头函数。比如
改写成下面这样的
结果显示this是undefined,我就感觉箭头函数的this有坑,研究了一番,发现还真的不一样。
箭头函数this指向与普通函数不同
箭头函数的this指向函数定义时的作用域,普通函数的this指向函数调用时的作用域。
因为箭头函数没有自己的上下文。
完整地例子参考这里:http://jsbin.com/vetecagupa/edit?js,console
注:在非严格模式执行
这个例子会输出1,因为普通函数的this指向函数被调用时候的作用域,也就是demo
这个例子会输出10,因为test1函数在定义的时候处于global作用域,调用的时候this维持不变。
这个例子会报错,因为函数test2定义的时候处于global作用域,所以调用的时候this指向global,而global中不存在test2方法。
回到render函数
搞清楚了箭头函数的this问题,但是由于我还没搞清楚react定义组件的时候作用域的问题,所以暂时没办法搞明白如何在组件中使用箭头函数,以后有时间再研究研究,未完待续。。。。
The text was updated successfully, but these errors were encountered: