When do I want to use "class" (static) methods or properties in JavaScript?

In JavaScript, why do you need to bind properties directly to the constructor?

var Human = function() {}; Human.specie = "Homo Sapience"; 

I have this question after looking at the CoffeeScript __extend helper function that contains among the lines:

 for ( var key in parent ) { if ( __hasProp.call( parent, key ) ) child[key] = parent[key]; } 

which copies the properties / methods for the subclass object directly from the constructor object. But why would anyone do this?

Thanks!

+6
source share
3 answers

In short, the answer to the question posed is the distance between the names . There are certain values โ€‹โ€‹that may make sense for sharing in your program and are semantically related to a particular class. These functions and values โ€‹โ€‹can simply be placed in some variables, but their binding to a design function is practical in order to put them down.

The best example is the JavaScript Math class (for purists, I know this is not really a class, this is an object):

 // There are constants Math.E Math.PI Math.SQRT2 // And there are also methods Math.ceil Math.cos Math.sin 

Thus, the methods and values โ€‹โ€‹(stored in constants) are always the same, and they do not depend on the instance on which they are called, and it makes no sense to have them on instances.

0
source

( Edit: In the original form, the question is about attaching properties to classes and attaching them to prototypes, so what I answer.)

This is indeed more arbitrary than anything else. If you write

 Human::specie = "Homo sapiens" 

(where Human::specie is CoffeeScript short 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, it sounds desirable.

But in other cases, having a property shared by a large number of prototypes makes it difficult to understand your code. Say you have a Logger class with a config object. If you attach this object to a prototype, you can write code like this:

 log = new Logger log.config.destination = './foo' 

This will change the assignment of all Logger instances to './foo' because there is only one config object. If you want config applied to all instances of Logger , you must attach it to the class, removing the ambiguity from the above code:

 log = new Logger Logger.config.destination = './foo' 
+2
source

The game says that you have an object called the world. However, the game will only have one world. This is theoretically the reason why you do this.

+1
source

Source: https://habr.com/ru/post/891616/


All Articles