I'm developing a javascript library, composed by a main object, that works as a static Class and contains various objects that do the same thing.
I am having trouble finding the best way to refer to the objects in the documentation, as i am using jGrouse and it refers to them as Classes, like:
public Class myLibrary
None of these objects and it's children will have any primitive type variables nor will have any factory pattern associated so, they are not to be reinstantiated.
I can't show you a live example, but i'll try to put here an analogous one:
var myLibrary = {};
myLibrary.methodOne = function(){ ... };
myLibrary.methodTwo = function(){ ... };
// this is a sub-library that will encapsulate methods for Array type operations
myLibrary.Array = {};
myLibrary.Array.forEach = function(array, function(item));
(...)
// this is a sub-library that will encapsulate methods for Event type operations
myLibrary.Events = {};
(...)
So, i don't think it's correct to refer to myLibrary, myLibrary.Array and myLibrary.Events as Classes, for the obvious reason that they are not meant to be instantiated.
I reject the idea to call them Static Classes as Javascript isn't design to work with static classes per se.
I think Object and Inner Object or Static Object may not be the way to go also.
I'm looking for the best way to identify them in my public documentation, as for not to confuse unexperienced programmers nor insult the more advanced developers.
Any help?
thanx
Your probably looking for the term "namespace".
You really shouldn't worry so much about the correct word. The are all far too vague and have completely separate meaning is several different meanings in JavaScript sub cultures.
The important thing to say in documentation is that "The Event has these methods".
I want to see the method signatures, I want to see a high level description of what they do and I want to see an example.
Related
I have pretty big javascript class with bunch of methods stored in a single js file. This methods can be logically categorized like common methods, methods to filter data, navigation methods etc. Now I want this class being split by separate files each containing its own specific category methods and leaving all properties and common methods in the current file. Shortly speaking I need something that c# partial keyword is used for.
I would like to avoid using prototype as it means I have to type class name for every function like class.prototype.functionname = function () { ... } that does not look great.
UPDATE: This is how my class looks like
function MyClass() {
var self = this;
self.common = function() {...}
self.filterData = function() {...}
self.navigate = function() {...}
}
I do not know how to handle self properly with prototypes or extension
If your class does not use the prototype, you have little chance - it is one [too] big function. However, such big functions shouldn't exist anyway, are you sure you need it to be a class (with multiple instances)? Then you should move the functions to the prototype as far as you can. If not, a singleton would make more sense for you, which is essentially nothing more than an object literal. You also might have a look at the [revealing] module pattern, which is what you need (or one of its flavors) - the (sub) modules usually can be spread easily across different files, potentially using a dependency tracking loader.
If it does, you can easily split it up into the single parts. That does not mean you would need to repeat class.prototype.… = …, you can just use helper functions like extend
MyFavLibrary.extend(class.prototype, {
functionname: function functionname() {…},
…
});
or a simple IEFE-closure:
(function(proto) {
// even some place for static, private helper functions
proto.functionname = functionname() {…};
…
})(class.prototype);
I want to pull a tree structured set of objects from a web service represented with JSON
When I unpack that, I'll wind up with a structure which uses vanilla Javascript objects. What I'd like to be able to do is bind each node to a specific class, so that method calls become available on each node of the tree.
My solution, using jQuery .extend()
Here's a simplified example which illustrates the approach.
I might define a simple class using jQuery .extend() as follows...
MyNode= function() {
this.init();
}
$.extend(MyNode.prototype, {
init: function() {
// do initialization here
},
getName: function() {
return this.nodeName;
}
});
Now given a simple object like this
var tree={
nodeName:'frumious',
nodeType:'MyNode'
}
I can make the object appear to be an instance of the desired nodeType with
$.extend(tree, eval(tree.nodeType+'.prototype'));
Note that I want the object to declare the class name, so I've used eval to locate the appropriate prototype for that class. (Thanks to Rob W for suggesting window[tree.nodeType].prototype as a better alternative)
Now I can do things like alert(tree.getName());
Better ways?
I write StackOverflow questions and find the act of describing it in enough detail to avoid a downvote is enough for me to solve it myself. This was no exception, but I'd be interested to hear of any more elegant approaches to this problem. This solution gets the job done, but I can't help but feel there must be other approaches...
I'd get rid off eval, and use:
$.extend(tree, window[tree.nodeType].prototype);
If MyNode is a local, but known variable, add it to an object, for reference. Eg:
var collection = {};
collection['MyNode'] = MyNode;
$.extend(tree, collection[tree.nodeType].prototype);
Alternatively, if the structure of the JSON is solid, I recommend a custom JSON parser, which also allows you to validate properties prior addition.
In JavaScript, why would one want to attach properties directly to the constructor?
var Human = function() {};
Human.specie = "Homo Sapience";
I've got this question after looking at CoffeeScript‘s __extend helper function, which contains, among the lines:
for ( var key in parent ) {
if ( __hasProp.call( parent, key ) ) child[key] = parent[key];
}
which copies properties / methods to the subclassed object directly from the constructor object. But why would anybody do that?
Thanks!
(Edit: In its original form, the question asked about attaching properties to classes vs. attaching them to prototypes, so that's what I'm responding to.)
It's really more a matter of convention than anything else. If you write
Human::specie = "Homo sapiens"
(where Human::specie is CoffeeScript shorthand for Human.prototype.specie) then declare jane = new Human, then jane.specie will be "Homo sapiens" (unless you specifically set jane.specie to something else). In this case, that sounds desirable.
But in other cases, having a property shared across a large number of prototypes makes your code harder to understand. Let's say that you have a Logger class with a config object. If you attached that object to the prototype, then you could write code like this:
log = new Logger
log.config.destination = './foo'
This would change the destination of all Logger instances to './foo', because there's only one config object. If you want config to apply to all Logger instances, then you should attach it to the class proper, removing the ambiguity from the code above:
log = new Logger
Logger.config.destination = './foo'
In a game say you have an object called world. However there will only ever be one world in the game. This is theoretically the reason you would do this.
In short the answer to the question posted is name spacing. There are certain values that may have sense to be shared across your program and that semantically have to do with certain class. These functions and values could be just put in some variables, but attaching them to constructor function is practical in order to namespace them.
The best example is JavaScript Math class (for purists, I know it's not really a class, it's an object):
// There are constants
Math.E
Math.PI
Math.SQRT2
// And there are also methods
Math.ceil
Math.cos
Math.sin
So the methods and values (saved in constants) are always the same and they don't depend on instance that they are being called on and it makes no sense to have them on instances.
I have a set of classes that work together (I'm coding in javascript).
There is one parent class and a number of child classes that are instantiated by the parent class. I have a number of clients of these classes that each need to add one or more methods to the parent or child classes.
Rather than having each client inherit from these classes, which is doable but messy because of the child classes, I am having these clients pass functions into the parent class when they instantiate the main class.
The main class creates the methods dynamically and the clients can call the methods like they were there all along.
My questions are:
is this a sensible thing to do?
what would the design pattern be for what I am doing?
The strategy pattern is for situations where you get your 'strategy' at runtime. might be applicable here. Strategy in this case is a class that conforms to a behavior, i.e. has a method like 'execute' or whatever.
The decorator pattern also might apply. It is also a runtime pattern, but augments the class it is decorating at the method level.
So the Strategy pattern is good if you are choosing a class dynamically, and Decorator is good if you are only changing out the method implementation at runtime.
(I took the decorator part of this answer with permission from ircmaxell)
I must admit that patterns aren't my "thing" - but you can do exactly what you want to in javascript. It is how all of the frameworks accomplish that sort of things "extending" child "classes" (there are no classes in javascript).
If you are in the pure javascript world, you want to use:
foo.prototype.bar = function() {};
So you can call bar on any foo, and bar only exists in memory once - that is the same function is referenced in memory through every foo object. So be careful with any variables you might be referencing outside that scope.
Each library has their own plugin architecture to accomplish roughly the same goal (and they take care of some of the messiness/danger in prototype)
You should provide some code, so that we can get a feel for what exactly you're talking about.
As you haven't: I can only guess that you're not making use of prototypes. Prototypes would be the "correct" design pattern for "object-oriented" JavaScript.
When you add a function/property/whatever to the prototype of an object in JavaScript, all instances, new and old receive the function/property/whatever on their prototype.
Extending prototypes in JavaScript is very simple, and should never become messy. If it does, it probably means you're over-complicating it.
As hvgotcodes says, you are describing the Strategy Pattern, the way you would do this for your specific case, is not to use prototypes (thereby affecting all objects of your class.)
Instead you'd provide a member that accepts a function as it's value.
e.g.
function MyClass() {
this.myFunction = defaultFunction;
this.defaultFunction = function() {
// do something by default.
alert("using default");
}
this.doFunction = function() {
// something that calls myFunction.
this.myFunction();
}
}
---8< snip --------
// later on...
t = new MyClass();
t.doFunction(); // output 'using default'
t.myFunction = function(){
// do something specific with this instance, when myFunction is called.
alert("customized for this instance.");
}
t.doFunction(); // output 'customized for this instance.'
Forgive my probably incorrect application of terminology in this question (btw, please correct me where wrong).
Let's say we have a custom object we want to define. Some of the methods on this object make sense to be 'instance' specific. And we also have some methods that are really independent of the instance, sort of like a public static method in a language like C# or Java.
What is the standard practice for creating these functional definitions? Currently, I am doing something like this:
var User = function(name){
this.Name = name;
User.instances.push(this);
};
User.instances = [];
User.doSomething = function(){
// do something interesting with the set of user instances
};
var me = new User('me');
var you = new User('you');
User.instances; // => [me, you]
Notice how the 'static' methods get defined in a completely different section from the prototype/instance methods. They just don't feel connected looking at the code. In my ideal world, I would be able to define everything together (perhaps inside the User = function(){}?), to keep the code a little cleaner and connected. I understand one of the powers of JS is you can do things separate and modify on the fly. Just curious what the standard practice is on something like this.
Sometimes I just nest the 'static' definitions in some brackets - even though the brackets are actually syntactically meaningless:
// Static definitions
{
User.instances = [];
User.doSomething = function(){
// do something interesting with the set of user instances
};
}
Is there a standard practice that I am unaware of?
Your approach is perfectly fine, although you can - if you really insist - try to do wacky tricks like assigning these static attributes inside a constructor conditionally based on whether they were already assigned.
IMHO this will not make it more readable but will have worse performing code due to the test (if you create lots of these User objects)