Context
I am writing a JavaScript library, and I am finding that I don't know what the best way to support object creation. I came up with a list things that I am considering:
var obj = Library.newObj('object-type');
var obj = Library.newObj(Library.ObjectType); // Library.ObjectType is an object containing information about how to create the new object
var obj = Library.newObj(Library.ObjectType); // Library.ObjectType is an integer specifying the type
var obj = new Library('object-type');
var obj = new Library(Library.ObjectType); // Library.ObjectType is an object containing information about how to create the new object
var obj = new Library(Library.ObjectType); // Library.ObjectType is an integer specifying the type
var obj = new Library.ObjectType();
In particular, these objects should also have specifiable options. This would then look like
var obj = Library.newObj('object-type', { /* options */ });
var obj = Library.newObj(Library.ObjectType({ /* options */ }));
var obj = Library.newObj(Library.ObjectType, { /* options */ });
var obj = new Library('object-type', { /* options */ });
var obj = new Library(Library.ObjectType({ /* options */ }));
var obj = new Library(Library.ObjectType, { /* options */ });
var obj = new Library.ObjectType({ /* options */ });
// Or, when the user wants to change options separately:
obj.setOptions({ /* options */ });
obj.setOption1(val1).setOption2(val2);
I am thinking that I might not want to specify the object type simply by a string or an integer because this might be difficult to maintain and is not very extensible.
Question
What are the pros and cons of these variants? Is there a best-practice / convention that I am not aware of? Should I support multiple ways to create objects? (Or are there any other variants that I did not consider?)
My Specific Case
(The particulars of my situation are that I want to allow developers using the library to provide their own 'object creation templates' that work with the library, but the library will also provide some pre-made 'templates' (like Library.ObjectType
). Furthermore, I don't want to expose more than one thing (like Library
above) to the global namespace when used in the browser. But would still like to avoid dot-horror, eg:
Library.objects.objectCreator.createObject(Library.objects.objectTypes.ObjectType1);