In JavaScript, why would one want to attach properties directly to the constructor?
var Human = function() {};
Human.specie = "Homo Sapience";
I've got this question after looking at CoffeeScript‘s __extend
helper function, which contains, among the lines:
for ( var key in parent ) {
if ( __hasProp.call( parent, key ) ) child[key] = parent[key];
}
which copies properties / methods to the subclassed object directly from the constructor object. But why would anybody do that?
Thanks!
You should consider making a method static in Java : 1) If a method doesn't modify the state of the object, or not using any instance variables. 2) You want to call the method without creating an instance of that class.
Static properties are used when we'd like to store class-level data, also not bound to an instance.
The static properties and methods are assigned to the class function instead of to the prototype of the class function. So, we cannot call the static method and properties using the instance of the class.
A static method has two main purposes: For utility or helper methods that don't require any object state. Since there is no need to access instance variables, having static methods eliminates the need for the caller to instantiate the object just to call the method.
(Edit: In its original form, the question asked about attaching properties to classes vs. attaching them to prototypes, so that's what I'm responding to.)
It's really more a matter of convention than anything else. If you write
Human::specie = "Homo sapiens"
(where Human::specie
is CoffeeScript shorthand for Human.prototype.specie
) then declare jane = new Human
, then jane.specie
will be "Homo sapiens"
(unless you specifically set jane.specie
to something else). In this case, that sounds desirable.
But in other cases, having a property shared across a large number of prototypes makes your code harder to understand. Let's say that you have a Logger
class with a config
object. If you attached that object to the prototype, then you could write code like this:
log = new Logger
log.config.destination = './foo'
This would change the destination of all Logger
instances to './foo'
, because there's only one config
object. If you want config
to apply to all Logger
instances, then you should attach it to the class proper, removing the ambiguity from the code above:
log = new Logger
Logger.config.destination = './foo'
In a game say you have an object called world. However there will only ever be one world in the game. This is theoretically the reason you would do this.
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