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

时间:2021-05-29 12:41:58

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

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

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?

捕获量在哪里?

1 个解决方案

#1


2  

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.

好吧,有一件事突然出现在我面前的第一个样本是TinyMCE期望其扩展函数的参数的方法。

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.

浏览扩展源,它检查每个键值对是否未定义,只有在定义时才将它们添加到对象中。因此,在扩展类时可以使用一些额外的功能。

#1


2  

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.

好吧,有一件事突然出现在我面前的第一个样本是TinyMCE期望其扩展函数的参数的方法。

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.

浏览扩展源,它检查每个键值对是否未定义,只有在定义时才将它们添加到对象中。因此,在扩展类时可以使用一些额外的功能。