在 JavaScript 中公开方法。为什么是这个语法?

发布于 2024-11-09 17:09:35 字数 731 浏览 6 评论 0原文

我正在研究 TinyMCE 代码,并偶然发现了这种公开公共方法的方式:

tinymce.extend(this, {
    execCommand : execCommand,
    queryCommandState : queryCommandState,
    queryCommandValue : queryCommandValue,
    addCommands : addCommands
});

如果编写上述内容有什么好处可以使用下面的代码来代替(同一任务所需的代码行数更少,执行时间也更少!)

this.execCommand = execCommand;
this.queryCommandState = queryCommandState;
this.queryCommandValue = queryCommandValue;
this.addCommands = addCommands;

或者甚至更短,在对象声明中的某处:

execCommand: execCommand,
queryCommandState: queryCommandState,
queryCommandValue: queryCommandValue,
addCommands: addCommands

问题在哪里?

I was studying TinyMCE code and stumbled upon this way of exposing public methods:

tinymce.extend(this, {
    execCommand : execCommand,
    queryCommandState : queryCommandState,
    queryCommandValue : queryCommandValue,
    addCommands : addCommands
});

What is the benefit of writing the above if the below code can be used instead (with fewer lines of code and less execution time required for the same task!)

this.execCommand = execCommand;
this.queryCommandState = queryCommandState;
this.queryCommandValue = queryCommandValue;
this.addCommands = addCommands;

Or even shorter, somewhere in the declaration of an object:

execCommand: execCommand,
queryCommandState: queryCommandState,
queryCommandValue: queryCommandValue,
addCommands: addCommands

Where's the catch?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(1

秋千易 2024-11-16 17:09:35

好吧,让我惊讶的一件事是您拥有的第一个示例是 TinyMCE 需要其 extend 函数的参数

查看 extend 的源代码,它会检查每个键值对是否未定义,只有在已定义的情况下才将它们添加到对象中。因此,在扩展类时有一些有用的附加功能。

Well, one thing that jumps out at me is the first sample that you have there is the method in which the TinyMCE expects its arguments for its extend function.

Glancing at the source of extend, it checks each key value pair for undefined, only adding them to the object if they're defined. So, there's a little bit of added functionality that can be useful when extending a class.

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