ES6 中 funcName() {} 和 funcName = () => {} 的区别
Difference between funcName() {} and funcName = () => {} in ES6
我最近一直在学习 React Native,我需要在组件完成后访问自定义组件的属性,例如感动。我定义了以下组件:
export class OperationBox extends React.Component {
constructor(props) {
super(props);
}
startOperation() {
Alert.alert("starting operation " + this.props.operation);
}
render() {
return (
<TouchableHighlight onPress={this.startOperation}>
<Text>{this.props.operation}</Text>
</TouchableHighlight>
);
}
}
当组件被触摸时应用程序崩溃说 undefined is not an object when evaluating this.props.operation
。但是,如果我这样定义函数 startOperation()
:startOperation = () => { ... }
,我会得到预期的行为。
现在,我想我理解了这些箭头函数是如何工作的。来自 Swift 背景,我认为它们就像闭包一样,但我肯定遗漏了什么?为什么第一种方式不行,第二种方式可以?
因为函数未绑定到 class 如果定义为:
someFunction() { }
如果定义为:
,则绑定
someFunction = () => { }
另一种可能性是在构造函数中显式绑定它:
constructor(props) {
super(props);
this.someFunction = this.someFunction.bind(this);
}
不同之处在于startOperation
函数作为回调传递,并在不同的环境中执行(初始class之外),所以this
指的是不同的对象。
简单答案:
在 ES6 Classes
funcName() {}
创建 "Class Methods" 但 funcName = () => {}
不创建。
关于所有 ECMASCRIPT 2015 语法 标准。
但是,您可以克服它 ;)
我最近一直在学习 React Native,我需要在组件完成后访问自定义组件的属性,例如感动。我定义了以下组件:
export class OperationBox extends React.Component {
constructor(props) {
super(props);
}
startOperation() {
Alert.alert("starting operation " + this.props.operation);
}
render() {
return (
<TouchableHighlight onPress={this.startOperation}>
<Text>{this.props.operation}</Text>
</TouchableHighlight>
);
}
}
当组件被触摸时应用程序崩溃说 undefined is not an object when evaluating this.props.operation
。但是,如果我这样定义函数 startOperation()
:startOperation = () => { ... }
,我会得到预期的行为。
现在,我想我理解了这些箭头函数是如何工作的。来自 Swift 背景,我认为它们就像闭包一样,但我肯定遗漏了什么?为什么第一种方式不行,第二种方式可以?
因为函数未绑定到 class 如果定义为:
someFunction() { }
如果定义为:
,则绑定someFunction = () => { }
另一种可能性是在构造函数中显式绑定它:
constructor(props) {
super(props);
this.someFunction = this.someFunction.bind(this);
}
不同之处在于startOperation
函数作为回调传递,并在不同的环境中执行(初始class之外),所以this
指的是不同的对象。
简单答案: 在 ES6 Classes
funcName() {}
创建 "Class Methods" 但 funcName = () => {}
不创建。
关于所有 ECMASCRIPT 2015 语法 标准。
但是,您可以克服它 ;)