Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extending javascript with keywords

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.

like image 965
jd. Avatar asked Oct 01 '09 20:10

jd.


People also ask

Can you extend built-in types JavaScript?

Built-in classes like Array, Map and others are extendable also. Please note a very interesting thing. Built-in methods like filter , map and others – return new objects of exactly the inherited type PowerArray .

Can you extend 2 classes in JavaScript?

No, in JavaScript, a class cannot extend from multiple classes, which is also known as “multiple inheritance”. In JavaScript, objects can only be associated with a single prototype, and extending multiple classes would mean that an object associates with multiple prototypes, which is not possible.

Which of the below keywords is used to extend a class from another?

Extends: In Java, the extends keyword is used to indicate that the class which is being defined is derived from the base class using inheritance. So basically, extends keyword is used to extend the functionality of the parent class to the subclass.

How do you inherit in JavaScript?

JavaScript super() keyword log(`Hello ${this.name}`); } } // inheriting parent class class Student extends Person { constructor(name) { console. log("Creating student class"); // call the super class constructor and pass in the name parameter super(name); } } let student1 = new Student('Jack'); student1. greet();


2 Answers

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.

like image 64
annakata Avatar answered Oct 13 '22 22:10

annakata


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.

like image 37
Anderson Green Avatar answered Oct 14 '22 00:10

Anderson Green