JavaScript factory for polymorphic objects approach - javascript

I am trying to build up a jQuery plugin using a factory approach since I need two differing objects with the same API. However, most of the examples I see use an inheritance method where some prefabbed object is constructed and then modified according to that objects needs. My question is, why is every approach I've seen some prefabbed object being constructed and then modified rather than simply building the object according to the options and then returning the public side of it using closures as a hook back into the private state of said object.
I don't think this is a duplicate, I have been looking around for my answer and have been fairly unlucky so far
Examples that clearly show what I mean:
- 1
- 2

Related

Why data binding doesn't always work with primitives?

One of the milestones in learning JS and Angular, is learning that two way data binding with primitives is tricky. If you want to make sure that databinding works, you should always pack it into an object - that is what I was told by some seniors in my company. My question is - why is that happening? What is exactly going on that makes databinding with primitives so compliated in JS?
I found out that Javascript passes objects by reverence, and primitives by value. So what exactly happens in for example AngularJS Controller, that enables us to bind primitive in ngModel?
EDIT
Any articles, pointers are more than welcome!
Here is good post or post.
In short:
"Primitive values (e.g. numbers, strings) are immutable in JavaScript. So whenever a change is made to them it means we are actually throwing away the previous instance and using a different one."

Use plain Javascript object as Ember model

Is it possible to use a plain JS object (say literal object) as model in EmberJS ?
All the examples that I see in the documentation use Ember.Object (or datastore)
I assume I might not get things like observable, etc using plain JS. But is it at least supported ?
This will not work reliably. A template such as
{{model.prop}}
operates by putting an observer on 'model.prop'. This might work in some cases, but not in others, or you may get weird Ember messages.
Of all the aspects of Ember, the most basic is the Ember object model. Essentially, the entire framework is based on this model and using it to manage objects and retrieve and set properties. Once you've bought into Ember, you've bought into using this object model, which is based on old-fashioned classic inheritance.
A common case where your issue comes up is that a server API returns a plain old JS object as the value of a model property. You then want to dig around inside that object, or display its properties in templates. In such cases, it is probably best to either convert the object to an Ember Object (you can do this with transforms; google and you will find people doing this); or, use embedded models, which is not trivial to do, and may require server-side changes (such as including an ID in the embedded models, although you could theoretically add one yourself in the adapter). The latter is what I have done and the end result was to pretty much maintain my sanity.

JavaScript: Constructors With Arguments And Inheritance Therefrom

I've signed up in the hope that someone can finally provide an exposition of Javascript's prototype inheritance that actually works. The specific code I'm interested in, centres upon a library I wrote myself to handle such tasks as the generation of linked lists, binary trees, etc., and for which I defined the following constructor:
function ListLinks(objLink)
{
this.prev = null;
this.next = null;
this.content = objLink;
}
The idea is that the 'prev' and 'next' properties are links to other ListLinks objects, and the 'content' property is a link to the object containing the data being inserted into the list or tree.
Now, using references to the prototype object associated with the above ListLinks object, I successfully added some class methods, to perform tasks such as entry insertion, entry removal, list traversal, and tree traversal. These all work nicely.
Now, because I want to take advantage of this functionality in a new object type, I thought that the intelligent approach would be to inherit that functionality, including all the properties and methods, from the ListLinks object in the new object. The new object I called a RenderTree object, because I'm interested in generating a binary tree of graphical rendering data. The idea being that I can sort my rendering data on input into the tree by distance from the viewing camera, and use an in-order traversal of the tree to implement the Painter Algorithm. But that isn't my problem.
My problem is persuading the JavaScript prototype inheritance mechanism to allow my RenderTree object to inherit the ListLinks object's properties and methods, without throwing all sorts of annoying bugs at me.
The trouble is, because the ListLinks constructor takes arguments, I can't create an instance of the ListLinks object and use that as my prototype in code such as:
RenderTree.prototype = new ListLinks(object);
because doing so forces ALL instances of RenderTree objects to have the 'content' property set to the same value, and even attempting explicitly to modify that value in created instances fails. Yet, without doing something of the above sort, I can't change the identity of the instantiated objects - they retain the identity of a ListLinks object (the parent), instead of acquiring the identity of the child (the RenderTree object), which was the whole point of using the above, and the subsequent:
RenderTree.prototype.constructor = RenderTree;
This was done so that the RenderTree object could inherit ALL of the ListLinks objects' properties and methods, yet have additional functionality added to facilitate the generation of the rendering data I intend to be inserted into a binary tree of RenderTree objects, said objects having their own distinctive identity.
Now, one of the weird aspects of this, from my standpoint, is that whilst the 'content' property of the RenderTree object becomes, in effect, immutable when doing this, the same isn't true of the 'next' and 'prev' properties. Which suggests to me that there's some horrible inconsistency lurking at the heart of the inheritance mechanism that will simply make me want to go back to class based languages, that don't exhibit this annoying behaviour. Performing the above task in a language such as C++, defining a ListLinks Class and then defining a RenderTree Class as an extension thereof, doesn't drop this unwanted hassle in my lap.
Now, to compound the issue, I've seen no less than four different expositions on the subject (two of them from here, as it happens), including using Object.create(), using super constructor invocation (this was covered in more detail on the page of one Ben Nadel), and using fake constructors. None of them I've tried has worked. All that happens is that previous methods that mostly worked in the old code end up being broken spectacularly when I try one of the new methods. Indeed, I initially learned about the whole business from the web page of someone called Toby Ho (I would have posted a link, but I've just been told I can't have two webpage links in my post, all helping to add to the frustration of trying to solve this problem, thank you), but that page was of no help with my particular problem either, other than solving the matter of allowing me to have class method functionality in my code.
Now, given the huge amount of frustration I've had over this, is it too much to ask, to see someone provide me with an explanation of this inheritance mechanism that [1] is in accord with the observations I've made above, [2] produces something that works, and [3] demonstrates that someone out there does actually understand what it's doing? Only I'm increasingly coming to the conclusion that whoever designed the latest incarnation of JavaScript just made up whatever looked good at the time, then threw it into the interpreter without giving a hoot about whether or not programmers trying to use it could make any sense of it.
If I can't alight upon some means of achieving what should be something trivial, and has been trivial in class based languages I'm familiar with, then I think I'll relegate JavaScript to the bin as far as serious work is concerned.

how are javascript properties added to and looked up on objects?

When adding properties to a JavaScript object are they added in an ordered way (alphabetical etc). And if so does that mean when you lookup a property on a JavaScript object that a quick algorithm is used like a binary tree search? I did a search for this and just found lots of explanations for prototype inheritance which I already understand I'm just interested in how a property is looked up within a single level of the prototype chain.
That entirely depends on the implementation. Google's V8 engine probably does it differently than Firefox's JagerMonkey. And they almost certainly does it different than IE6. Looking up a property in an object is just an interface (a fairly common Map interface as programmers would call it). The only thing Javascript guarantees you is the methods of the interface, no details about implementation, and that's a good thing. It could be a hash table (probably) or it could be a linked list (less likely, but possible) or it could even be a binary search tree.
The point is that we don't know how it's implemented, nor should we. And you should make no assumptions about the implementation. As is common with abstraction in programming, just assume it's magic. :)
Here is a high level description of how v8 does it using hidden classes it then looks up the property value by using the fixed offset provided by the definition of the hidden class. It also confirms that most other implementations use a dictionary type data object.

I want to stop using OOP in javascript and use delegation instead

After dabbling with javascript for a while, I became progressively convinced that OOP is not the right way to go, or at least, not extensively. Having two or three levels of inheritance is ok, but working full OOP like one would do in Java seems just not fitting.
The language supports compositing and delegation natively. I want to use just that. However, I am having trouble replicating certain benefits from OOP.
Namely:
How would I check if an object implements a certain behavior? I have thought of the following methods
Check if the object has a particular method. But this would mean standardizing method names and if the project is big, it can quickly become cumbersome, and lead to the java problem (object.hasMethod('emailRegexValidatorSimpleSuperLongNotConflictingMethodName')...It would just move the problem of OOP, not fix it. Furthermore, I could not find info on the performance of looking up if methods exist
Store each composited object in an array and check if the object contains the compositor. Something like: object.hasComposite(compositorClass)...But that's also not really elegant and is once again OOP, just not in the standard way.
Have each object have an "implements" array property, and leave the responsibility to the object to say if it implements a certain behavior, whether it is through composition or natively. Flexible and simple, but requires to remember a number of conventions. It is my preferred method until now, but I am still looking.
How would I initialize an object without repeating all the set-up for composited objects? For example, if I have an "textInput" class that uses a certain number of validators, which have to be initialized with variables, and a class "emailInput" which uses the exact same validators, it is cumbersome to repeat the code. And if the interface of the validators change, the code has to change in every class that uses them. How would I go about setting that easily? The API I am thinking of should be as simple as doing object.compositors('emailValidator','lengthValidator','...')
Is there any performance loss associated with having most of the functions that run in the app go through an apply()? Since I am going to be using delegation extensively, basic objects will most probably have almost no methods. All methods will be provided by the composited objects.
Any good resource? I have read countless posts about OOP vs delegation, and about the benefits of delegation, etc, but I can't find anything that would discuss "javascript delegation done right", in the scope of a large framework.
edit
Further explanations:
I don't have code yet, I have been working on a framework in pure OOP and I am getting stuck and in need of multiple inheritance. Thus, I decided to drop classes totally. So I am now merely at theoretical level and trying to make sense out of this.
"Compositing" might be the wrong word; I am referring to the composite pattern, very useful for tree-like structures. It's true that it is rare to have tree structures on the front end (well, save for the DOM of course), but I am developing for node.js
What I mean by "switching from OOP" is that I am going to part from defining classes, using the "new" operator, and so on; I intend to use anonymous objects and extend them with delegators. Example:
var a = {};
compositor.addDelegates(a,["validator", "accessManager", "databaseObject"]);
So a "class" would be a function with predefined delegators:
function getInputObject(type, validator){
var input = {};
compositor.addDelegates(input,[compositor,renderable("input"+type),"ajaxed"]);
if(validator){input.addDelegate(validator);}
return input;
}
Does that make sense?
1) How would I check if an object implements a certain behavior?
Most people don't bother with testing for method existance like this.
If you want to test for methods in order to branch and do different things if its found or not then you are probably doing something evil (this kind of instanceof is usually a code smell in OO code)
If you are just checking if an object implements an interface for error checking then it is not much better then not testing and letting an exception be thrown if the method is not found. I don't know anyone that routinely does this checking but I am sure someone out there is doing it...
2) How would I initialize an object without repeating all the set-up for composited objects?
If you wrap the inner object construction code in a function or class then I think you can avoid most of the repetition and coupling.
3) Is there any performance loss associated with having most of the functions that run in the app go through an apply()?
In my experience, I prefer to avoid dealing with this unless strictly necessary. this is fiddly, breaks inside callbacks (that I use extensively for iteration and async stuff) and it is very easy to forget to set it correctly. I try to use more traditional approaches to composition. For example:
Having each owned object be completely independent, without needing to look at its siblings or owner. This allows me to just call its methods directly and letting it be its own this.
Giving the owned objects a reference to their owner in the form of a property or as a parameter passed to their methods. This allows the composition units to access the owner without depending on having the this correctly set.
Using mixins, flattening the separate composition units in a single level. This has big name clash issues but allows everyone to see each other and share the same "this". Mixins also decouples the code from changes in the composition structure, since different composition divisions will still flatten to the same mixed object.
4) Any good resources?
I don't know, so tell me if you find one :)

Categories

Resources