Extending javascript with keywords

3.2k views Asked by At

My Google-ing on this has been unsuccessful, so here's the question:

I am wondering if it is possible to add my own keywords to extend the JavaScript language in a given framework.

For example

Object1 extends Object2

in the code would result in executing this method

inherit(Object1, Object2)

Where inherit is a function that takes care of copying the prototype, adding the parent's constructor, etc..

Is this doable? If so, how ? If not, any other nice way of doing this?

Thanks.

4

There are 4 answers

3
annakata On BEST ANSWER

You can't add keywords to the language but everything is an object and everything can be extended with prototyping.

I wouldn't normally link to crockford but he actually has quite a decent coverage of this , which will afford you syntax of the form foo.inherits(bar); which is about as good as one could wish for. This is quite a common pattern.

1
Alex Barrett On

It's not possible to add new keywords to JavaScript, no. You could create your own nice interface for creating classes though, perhaps drawing inspiration from one of the myriads of library, frameworks and toolkits out there already!

0
Anderson Green On

Several JavaScript macros systems have been developed for this purpose, including sweet.js. Using the Sweet.js macro system, you can replace one keyword with another keyword (for example, replacing the function keyword with a def keyword.) However, in order to run sweet.js scripts, you must first compile them to JavaScript using the sweet.js compiler.

0
Валерий Заблодский On

It is easy to do like:

window.inherit = function(...params){your code here}

You can call window's methods without recoursing to window object, so you will be able to call like inherit(arr1, arr2)