Extending javascript with keywords
Asked Answered
A

4

7

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.

Average answered 1/10, 2009 at 20:4 Comment(0)
K
6

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.

Katlin answered 1/10, 2009 at 20:8 Comment(3)
Why wouldn't you normally link to crockford?Average
Because I disagree with a great many things he says about my beloved javascript, and am of the opinion that his opinions are oft repeated without self consideration.Katlin
@Katlin Million times this. Glad I'm not alone on that opinion.Whitecap
C
5

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.

Closefitting answered 5/1, 2013 at 1:51 Comment(0)
D
1

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)

Dogleg answered 22/8, 2020 at 12:1 Comment(0)
I
0

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!

Insurance answered 1/10, 2009 at 20:8 Comment(1)
It actually is possible to create keywords for JavaScript using sweet.js. See my answer on this page. :)Closefitting

© 2022 - 2024 — McMap. All rights reserved.