When would I want to use “class” (static) methods or properties in JavaScript?
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 objec开发者_如何转开发t directly from the constructor object. But why would anybody do that?
Thanks!
(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.
In short the answer to the question posted is name spacing. There are certain values that may have sense to be shared across your program and that semantically have to do with certain class. These functions and values could be just put in some variables, but attaching them to constructor function is practical in order to namespace them.
The best example is JavaScript Math
class (for purists, I know it's not really a class, it's an object):
// There are constants
Math.E
Math.PI
Math.SQRT2
// And there are also methods
Math.ceil
Math.cos
Math.sin
So the methods and values (saved in constants) are always the same and they don't depend on instance that they are being called on and it makes no sense to have them on instances.
精彩评论