Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When is it okay to alias a JavaScript namespace, type, or method?

Our team is referencing Google's JavaScript Style Guide.

One section states, "Avoid accessing properties of an aliased type, unless it is an enum" but doesn't elaborate on why.

Aliasing a method changes the context of "this" according to the sample code we've ran based on this article.

However, I can't find a clear example of why you should not access properties of an aliased type? Does anyone have an example of why this would be bad?

like image 926
Nevada Williford Avatar asked Nov 01 '22 18:11

Nevada Williford


1 Answers

There's no such thing as a JavaScript namespace, method, or type. Okay, maybe there are things like methods (let's just call them functions), but namespaces and types can mean different things to different people. To Google, they mean whatever you find in their style guide.

JavaScript is a prototypal language devoid of some of the features found in C++ or Java (polymorphism, inheritance, namespaces, typing, Eve objects, etc.). The Google style guide (it's not the only one of its kind, see Douglas Crockford) presents a number of stylistic constraints. These constraints are often have no syntactic value, but are merely stylistic in nature (as my comment mentions).

For example, all namespaces need to be aliased via goog.scope. This may be used for closure compiler compatibility, readability, debugging, or just because it looks pretty. To address your question, it wouldn't be bad per se to access an aliased type's properties and even the issue you bring up (losing the this context) can be solved with something like .apply(...) or .bind(...).

Furthermore (and this is just me ranting), the term aliased type has a pretty concrete meaning in other languages; I think it's stupid to use it in the context of JS -- which is has an incredibility vague idea of types to begin with.

like image 179
David Titarenco Avatar answered Nov 12 '22 20:11

David Titarenco