使用关键字扩展 javascript

发布于 2024-08-06 14:16:54 字数 304 浏览 1 评论 0原文

我对此的 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

野心澎湃 2024-08-13 14:16:54

您无法向语言添加关键字,但一切都是对象,并且一切都可以通过原型进行扩展。

我通常不会链接到 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.

守不住的情 2024-08-13 14:16:54

为此目的开发了几个 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 a def keyword.) However, in order to run sweet.js scripts, you must first compile them to JavaScript using the sweet.js compiler.

终遇你 2024-08-13 14:16:54

这很容易做到:

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

您可以调用 window 的方法,而无需调用 window 对象,因此您将能够像 inherit(arr1, arr2) 那样进行调用

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)

梦里°也失望 2024-08-13 14:16:54

不可能向 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!

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文