最近在写React,在定义一个class的方法时,看到了如下fun1和fun2这两种写法,用起来都没有问题。看了下阮大师的入门指南,发现都是fun1这种写法,那么这两种写法有啥区别呢?
class MyClass {
name = 1;
fun1() {
console.log(this.name);
}
fun2 = () => {
console.log(this.name);
}
}
最近在写React,在定义一个class的方法时,看到了如下fun1和fun2这两种写法,用起来都没有问题。看了下阮大师的入门指南,发现都是fun1这种写法,那么这两种写法有啥区别呢?
class MyClass {
name = 1;
fun1() {
console.log(this.name);
}
fun2 = () => {
console.log(this.name);
}
}
fun2 = () => {
console.log(this.name);
}
其实是
this.fun2 = () => {
console.log(this.name);
}
吧 是自定义属性 不是原型方法 这种定义属性的方法目前也没正式进入规范
是this
指向的问题:
React 组件书写大多使用 class 构造器写成,这里的 this 指向需要确保绑定在 class 类所构造出来的组件上面
class Component3 extends React.Component {
submit(e){
console.log(this)
e.target.style.color = 'red'
}
render(){
return <input type="button" value="submit3" onClick={this.submit.bind(this)}/>
}
}
class Component2 extends React.Component {
constructor(props) {
super(props);
this.submit = this.submit.bind(this);
}
submit(e){
console.log(this)
e.target.style.color = 'red'
}
render(){
return <input type="button" value="submit2" onClick={this.submit}/>
}
}
class Component1 extends React.Component{
submit(e){
console.log(this)
e.target.style.color = 'red'
}
render(){
return <input type="button" value="submit1" onClick={(e) => this.submit(e)}/>
}
}
或
class Component4 extends React.Component{
submit(e){
console.log(this)
e.target.style.color = 'red'
}
render(){
return <input type="button" value="submit" onClick={(e) => this.submit(e)}/>
}
}
对于我这个伪前端来讲,在定义方法的时候一般都是用fun1这个类型,为什么,因为代码少,用的多,功能都能实现;在导入组件及axios请求时都是用第fun2,为什么,因为都是这样用,因为有些功能fun1实现起来更复杂,也可能实现不了,具体什么两个定义的差别可以看楼上的回答
写代码最主要的是,实现功能即可。
这两种写法,你需要理解的只有两点,this的指向 和 箭头函数和普通函数this的区别。
1.普通函数,this是在函数执行时候才确定的。谁调用这个函数,this指向谁,或者,手动call,apply指定this,或者bind生成一个指定了this的未调用函数。
2.箭头函数,this是在函数声明的时候,代码解析到声明表达式的时候,这时候this是谁就是谁。类似于普通函数+bind。
应用场景,个人觉得遇到的最多的情况,就是把A中有this的函数fn传到别的地方,在非作用域为A的情况下调用函数fn。这时候,可能你希望的是fn中的this指向的是A。这就需要你在A中声明时候声明成箭头函数,或者传递时候传递的是fn.bind(A)。
不只是React,我没用过React。这个知识点应该是js的语言特性,任何框架里面都是一样的。
10 回答11.1k 阅读
6 回答3k 阅读
5 回答4.8k 阅读✓ 已解决
4 回答3.1k 阅读✓ 已解决
2 回答2.7k 阅读✓ 已解决
3 回答2.3k 阅读✓ 已解决
3 回答2.1k 阅读✓ 已解决
react文档读了吗?
图中链接在此