What is the meaning of static get in Javascript?

2

An expression in Javascript has left me a bit confused:

static get is() { return "custom-element"; }

What is the operation of a static get in Javascript? I guess the static has a function similar to what is done in Java or C ++.

    
asked by Cesar Jr Rodriguez 19.03.2017 в 17:30
source

1 answer

3

It is the way to define getters and setters in EcmaScript 6, also called accessors. The accessors are used to access private properties of an instance as if the property were accessed directly, but in reality access is done through a function. This allows to maintain a control over what is read and what is written in the property, keeping the property private. In this way, all kinds of validations or transformations can be made to the input data to maintain the logical coherence of the instance. On the Internet you can surely find more detailed and complete explanations of its use that is improvised explanation.

Regarding the syntax, the thing has crumb. Although JavaScript inherits a lot of Java and C ++ things, you have to be careful because it also has very different things, mainly its dynamism. JavaScript is a language whose object orientation is based on the inheritance of prototypes instead of classical inheritance such as C ++ or Java.

The code that you use uses the new form added to JavaScript to facilitate the use of the language in a way more similar to the classical inheritance. In fact, if we compare it with the classical heritage there is something strange. The code defines a method, is() , statically. This, in POO of classic inheritance would imply that the method only has access to the properties and static methods of the class, but it could not be executed on an instance. However, as I indicated earlier, JavaScript has an inheritance based on prototypes. Suffice it to say that the objects have a parent prototype from which they inherit their methods (in JavaScript there are not really classes, although class has been added).

The code that you comment is what you do is add the getter id () to the constructor of the instance, which is in JavaScript the prototype of the instance. In this way, the getter is only defined at one point (in the object that builds the instances) but is available for all instances.

NOTE : In JAvaScript, if you try to execute a method that does not exist in an instance, the JavaScript engine looks for that same method in the prototypes of the instance. If it finds it, it executes it; If you finish searching all the prototypes without finding it, an error will be thrown.

    
answered by 19.03.2017 в 17:53