使用关键字扩展 javascript
我对此的 Google 搜索不成功,所以问题是:
我想知道是否可以添加我自己的关键字来扩展给定框架中的 JavaScript 语言。
例如,
Object1 extends Object2
在代码中将导致执行此方法
inherit(Object1, Object2)
,其中继承是一个负责复制原型、添加父级构造函数等的函数。
这可行吗?如果是这样,怎么办?如果没有,还有其他好的方法吗?
谢谢。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您无法向语言添加关键字,但一切都是对象,并且一切都可以通过原型进行扩展。
我通常不会链接到 crockford,但他实际上对此有相当不错的报道,它将为您提供
foo.inherits(bar);
形式的语法,这几乎是人们所希望的那样好。这是一种很常见的模式。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.为此目的开发了几个 JavaScript 宏系统,包括 sweet.js。使用 Sweet.js 宏系统,您可以将一个关键字替换为另一个关键字(例如,替换
function
关键字与def
关键字。)但是,为了运行 sweet.js 脚本,您必须首先使用 sweet.js 编译器将它们编译为 JavaScript。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 adef
keyword.) However, in order to run sweet.js scripts, you must first compile them to JavaScript using the sweet.js compiler.这很容易做到:
您可以调用 window 的方法,而无需调用 window 对象,因此您将能够像
inherit(arr1, arr2)
那样进行调用It is easy to do like:
You can call window's methods without recoursing to window object, so you will be able to call like
inherit(arr1, arr2)
不可能向 JavaScript 添加新的关键字,不是。不过,您可以创建自己的漂亮界面来创建类,也许可以从现有的无数库、框架和工具包之一中汲取灵感!
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!