Mascara: Next Generation JavaScript compiler

Try it Download Buy About Documentation Blog Contact

Prototypes

Classic JavaScript supports only prototype inheritance. ECMAScript 4 additionally supports a more traditional class-based inheritance.

Prototypes can still be used in ECMAScript 4. Prototypes are especially useful for "monkeypatching", i.e. attaching new methods to existing built-in types, like String, Array etc.

There is however some limitations compared to how you can use it in ordinary JavaScript. You can assign directly to the prototype on a class:

String.prototype.shuffle = function() {...}
However, you cannot assign to a variable expression:
var cls = String;
cls.prototype.shuffle = function(){...} <-- ERROR!
This will generate a compile-time error, since a variable may change, and therefore the type-engine cannot be completely sure what object we are assigning to. You can however do this:
const cls = String;
cls.prototype.shuffle = function() {...}
Because a 'const' is constant, and therefore can always be resolved by the compiler. Most patterns using prototypes assign directly to the target as in the first example, however some more clever patterns are more dynamic and can sadly not be verified statically.

Another caveat: Usually we assign to prototypes of constructor functions. But as the example with String shows, we can also assign to the prototype of a class. However:

1) the class has to be declared as dynamic before we can modify the prototype.

2) You shouldn't modify the prototype on objects that also uses class-based inheritance, since the interaction between class-based inheritance and prototype-based inheritance is undefined. If B extends A, and you modify B.prototype, then you may or may not change the behavior of A, depending on the phases of the moon.

X Try!
Mascara JavaScript Generated JavaScript

Translating...
Show compiler settings