[英]ES6 React - static method vs constructor
I'm running into an "issue" where I don't know which one is the best option. 我遇到了一个“问题”,我不知道哪个是最佳选择。
Say I have the following class 说我有以下课程
export default class A {
constructor(){
this.testMethod = function testMethod(){
console.log('a')
}
}
static testMethod2 = function() {
console.log('B')
}
}
now I'm extending this class 现在我要扩展这堂课
class C extends A {
fetch() {
this.testMethod()
A.testMethod2()
}
}
Defining it as a static method feels weird to use when extending it, I would assume the fact that I'm extending a class would allow me to access all of its own methods (ES5 prototype style) 在扩展它时,将其定义为静态方法感觉很奇怪,我假设我正在扩展一个类的事实将允许我访问其所有方法(ES5原型样式)
I know both ways are correct but what's the best way to do this in ES6/React ? 我知道两种方法都是正确的,但是在ES6 / React中做到这一点的最佳方法是什么? What are some caveats of both ways or performance issues ?
这两种方式或性能问题都有哪些警告?
I'm currently using the constructor because it feels like the right/intended way of doing it but I can't "justify" one over the other. 我目前正在使用构造函数,因为它感觉像是正确的/预期的方式,但是我不能在另一个之上“合理化”。
All this came from applying the airbnb eslint to my code base ( http://eslint.org/docs/rules/class-methods-use-this ) 所有这些都来自将airbnb eslint应用于我的代码库( http://eslint.org/docs/rules/class-methods-use-this )
I would assume the fact that I'm extending a class would allow me to access all of its own methods
我假设我正在扩展一个类,这将允许我访问其所有方法
You actually can do that. 您实际上可以做到。 Just call
C.testMethod2()
instead of A.testMethod2()
(or even use this.constructor.testMethod2()
). 只需调用
C.testMethod2()
而不是A.testMethod2()
( 甚至使用this.constructor.testMethod2()
)。
Defining functions that have nothing to do with a particular instance on the prototype or even inside the constructor is a bad practise, don't do that. 在原型上,甚至在构造函数内部,定义与特定实例无关的函数都是不好的做法,不要这样做。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.