简体   繁体   English

您应该如何设计具有多功能构造函数的库?

[英]How should you design a library with a multifunctional constructor?

Recently I was playing around with writing a small library for music theory in JS. 最近,我在玩一个小型的JS音乐理论库。 One of the features I wanted to add was a jQuery style selector for creating/finding notes. 我要添加的功能之一是用于创建/查找笔记的jQuery样式选择器。 For example: 例如:

Notes("a#") === Note {_note: 0, accidental: 1}

However, the structure of the library looked something akin to: 但是,该库的结构类似于以下内容:

var Notes = function(sel) {

   // initialisation stuff
   var Note = function() {
        // stuff for note objects
   };

   var scales = {
       ...
   };

   var selector(sel) {
        // evaluate sel
        return new Note(...);
   };

   if(sel !== undefined) {
       return selector(sel);
   }

   return {
       Note: Note,
       scales: scales
   };
};
module.exports = new Notes();

This way, I could use the library like this: 这样,我可以像这样使用库:

var Notes = require("Notes");
Notes.scales.major.c === [0,2,4,...];

But not like this: 但不是这样的:

var thisNote = Notes("A#");

As Notes was obviously an object that had been returned from the original Notes function. 由于Notes很明显是从原始Notes函数返回的对象。 To use the selector function I'd have to expose it and then call it like this: 要使用选择器功能,我必须公开它,然后像这样调用它:

var thisNote = Notes.selector("A#");

But I want to mimic the jQuery/sizzle style (I had a bit of a search of jQuery's source, but couldn't find anything that helped). 但是我想模仿jQuery / sizzle的风格(我搜索了jQuery的源代码,但是找不到任何有用的方法)。

How can I/should I have approached the design to allow for this kind of functionality? 我/应该如何进行设计以允许这种功能? Would using prototypes instead of Closures been a more sensical approach? 使用原型而不是闭包会更明智吗? Or should I have aliased the library's name to another method to achieve the desired effect? 还是应该将库的名称别名为另一种方法以达到预期的效果?

jQuery is like this: jQuery就像这样:

function wrap() {
    // do wrapping of DOM nodes
    return {
        value: function () { /*..*/ },
        add_class: function () { /*..*/ }
    };
}
wrap.extend = function () { /*..*/ }
wrap.ajax = function () { /*..*/ }

wrap("#abc"); // has `.value` and `.add_class)
wrap.ajax();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM