I am using Webstorm
and I wrote a React component, my code looks like:
async onDrop( banner, e ) {
banner.classList.remove( 'dragover' );
e.preventDefault();
const file = e.dataTransfer.files[ 0 ], reader = new FileReader();
const { dispatch } = this.props;
const result = await this.readFile( file, reader );
banner.style.background = `url( ${ result } ) no-repeat center`;
dispatch( addLayer( file ) );
return false;
}
@isImage( 0 )
readFile( file, reader ) {
reader.readAsDataURL( file );
return new Promise( function ( resolve, reject ) {
reader.onload = ( event ) => resolve( event.target.result );
reader.onerror = reject;
} );
}
onDragOver( banner ) {
banner.classList.add( 'dragover' );
return false;
}
Webstorm's code inspection suggest me that Method can be static
for the onDragOver
method. My question is:
Are there any real benefit from having the method as static or this suggestion is somehow useless?
static elements are accessible from any context (i.e. anywhere in your script), so you can access these methods without needing to pass an instance of the class from object to object.
They are faster — Static methods are slightly faster than instance methods because in instance methods, you are also working with an implicit this parameter. Eliminating that parameter gives a slight performance boost in most programming languages.
The most important reason why static keywords are heavily used in Java is to efficiently manage memory. Generally, if you want to access variables or methods inside a class, you first need to create an instance or object of that class.
Yes, you don't need an instance of the object when invoking a static function. All you need is a reference to the constructor:
class Foo {
static bar() { console.log("foo"); }
}
Foo.bar(); // outputs "foo" to console
No need for a new Foo()
anywhere.
By convention, instance methods should be used when you actually need state (either to read state, or to write state) from an instance.
The inspection will tell you that when you have a prototype/class method that does not have a this
in it (and thus doesn't need an instance).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With