在 JavaScript 中公开方法。为什么是这个语法?
我正在研究 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
好吧,让我惊讶的一件事是您拥有的第一个示例是 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 forundefined
, 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.