What object oriented design patterns do you use in your application's javascript, and why?
Feel free to post code, even if there is no formal design pattern attached to it.
I have written plenty of javascript, but I have not applied much object orientated patterns to what I am doing, and I am sure i am missing a lot.
The following are three popular JavaScript patterns. These happen to be easily implementable because of closures:
The Module Pattern - Example (and made popular) by Eric Miraglia
Memoization - Example by Oliver Steele
Currying - Example by Dustin Diaz
You may also want to check out:
Pro JavaScript Design Patterns by Ross Harmes and Dustin Diaz
The following is a Google I/O talk from 2008 presented by Diaz, where he discusses some topics from his book:
Google I/O 2008 - Design Patterns in an Expressive Language
Inheritance
I use a notation for inheritance that is based on ExtJS 3, which I find works pretty close to emulating classical inheritance in Java. It basically runs as follows:
// Create an 'Animal' class by extending
// the 'Object' class with our magic method
var Animal = Object.extend(Object, {
move : function() {alert('moving...');}
});
// Create a 'Dog' class that extends 'Animal'
var Dog = Object.extend(Animal, {
bark : function() {alert('woof');}
});
// Instantiate Lassie
var lassie = new Dog();
// She can move and bark!
lassie.move();
lassie.bark();
Namespaces
I also agree with Eric Miraglia on sticking to namespaces so the code above should be run within its own context outside the window object, this is critical if you intend your code to run as one of many concurrent frameworks / libraries executing in the browser window.
This means that the only way to the window object is via your own namespace / module object:
// Create a namespace / module for your project
window.MyModule = {};
// Commence scope to prevent littering
// the window object with unwanted variables
(function() {
var Animal = window.MyModule.Animal = Object.extend(Object, {
move: function() {alert('moving...');}
});
// .. more code
})();
Interfaces
You can also make use of more advances OOP constructs such as interfaces to enhance your application design. My approach to these is to enhance the Function.prototype in order to get a notation along these lines:
var Dog = Object.extend(Animal, {
bark: function() {
alert('woof');
}
// more methods ..
}).implement(Mammal, Carnivore);
OO Patterns
As for 'Patterns' in the Java sense, I've only found use for the Singleton pattern (great for caching) and the Observer pattern for event-driven functionality such as assigning some actions when a user clicks on a button.
An example of utilising the Observer Pattern would be:
// Instantiate object
var lassie = new Animal('Lassie');
// Register listener
lassie.on('eat', function(food) {
this.food += food;
});
// Feed lassie by triggering listener
$('#feeding-button').click(function() {
var food = prompt('How many food units should we give lassie?');
lassie.trigger('eat', [food]);
alert('Lassie has already eaten ' + lassie.food + ' units');
});
And thats just a couple of tricks in my bag of OO JS, hope they are useful to you.
I recommend if you intend to go down this road that you read Douglas Crockfords Javascript: the Good Parts. Its a brilliant book for this stuff.
I am a fan of the Module Pattern. It's a way of implementing extensible, non-dependent (most of the time) frameworks.
Example:
The framework, Q, is defined like this:
var Q = {};
To add a function:
Q.test = function(){};
These two lines of code are used together to form modules. The idea behind modules is that they all extend some base framework, in this case Q, but are not reliant on each other (if designed correctly) and can be included in any order.
In a module, you first create the framework object if it does not exist (which is an example of the Singleton pattern):
if (!Q)
var Q = {};
Q.myFunction = function(){};
That way, you can have multiple modules (like the one above) in separate files, and include them in any order. Any one of them will create the framework object, and then extend it. No manual need to check if the framework exists. Then, to check if a module/function exists in custom code:
if (Q.myFunction)
Q.myFunction();
else
// Use a different approach/method
The singleton pattern is often very helpful for 'encapsulation' and organization stuff. You can even change accesibility.
var myInstance = {
method1: function () {
// ...
},
method2: function () {
// ...
}
};
cleanest way to implement a singleton in javascript
I really like jquery's method chaining pattern, allowing you to call several methods on one object. It makes it really easy to perform several operations in a single line of code.
Example:
$('#nav').click(function() {
$(this).css('color','#f00').fadeOut();
});
I really like the Decorator pattern with jQuery plugins. Rather than modifying plugins to meet your needs, write a custom plugin that just forwards requests and adds additional parameters and functionality.
For example, if you need to pass a set of default arguments around all the time, and you need slightly-different behavior that ties into business logic, write a plugin that does whatever pre and post work is necessary to suit your needs and passes your default arguments if those particular arguments aren't specified.
The main benefit of this is that you can update your libraries and not worry about porting library changes. Your code might break, but there's at least the chance that it won't.
One of useful patterns in javascript world is chaining pattern which is made popular by LINQ at first place, and also is used in jQuery.
this pattern enables us to call different methods of a class in chaining manner.
the main structure of this pattern would be as
var Calaculator = function (init) {
var result = 0;
this.add = function (x) { result += (init + x); return this; };
this.sub = function (x) { result += (init - x); return this; };
this.mul = function (x) { result += (init * x); return this; };
this.div = function (x) { result += (init / x); return this; };
this.equals = function (callback) {
callback(result);
}
return this;
};
new Calaculator(0)
.add(10)
.mul(2)
.sub(5)
.div(3)
.equals(function (result) {
console.log(result);
});
the key idea of this pattern is this key word, which makes possible accessing to other public member of Calculator fucntion.
Related
The strategy pattern is software a design pattern to select an algorithm at runtime. See this javascript implementation for reference.
See the linked page, how the example use different classes at runtime. But, what about if you just want to select one function? Is it worth encapsulate those functions in classes? Or just select the function to use, like in the next snipped:
function getRandomThing() {
return Math.floor(Math.random() * thingsCount);
}
function getNextThing() {
return currentThing++ % thingsCount;
}
currentGetThing = getNextThing
currentGetThing()
Is this solution correct? It works, but currentGetThing = getNextThing sounds a bit C-liked for me.
Just select the function directly.
Is it worth encapsulate those functions in classes?
No. It's hardly ever worth to encapsulate anything in a class when you can do without - that many other languages cannot do without and require classes for everything should not affect your choice in JavaScript.
Also don't forget that functions already are objects in JavaScript, they're instances of the Function class. If you absolutely want to define an interface for them, just go for duck-typing their call method.
I believe you lack the Context, the part of your code which uses the algorithm and where you want the algorithm to be replaced with another one. Take a look at the UML class diagram of the Strategy pattern to find that the Context is a vital part of the pattern.
In statically-typed OO implementations of the pattern, the context uses the abstraction of the strategy and the abstraction is either an interface or an abstract class. However, passing just a function would of course work, too. It's more your style of the implementation rather than a requirement to implement it in any specific way.
What is missing in your snipped then is the context, what possibly raises your doubts about the C-like style. Just let the strategy function be passed to the context, just like you would pass the strategy object to a context in an OO-like language.
var thingsCount = 5;
var currentThing = 0;
function getRandomThing() {
return Math.floor(Math.random() * thingsCount);
}
function getNextThing() {
return currentThing++ % thingsCount;
}
// strategy passed as a function
function context(strategy) {
var result = strategy();
console.log(result);
}
// call the context with different strategies
context(getNextThing);
context(getRandomThing);
The javascript prototype-based object-oriented programming style is interesting, but there are a lot of situations where you need the ability to create objects from a class.
For instance in a vector drawing application, the workspace will usually be empty at the beginning of the drawing : I cannot create a new "line" from an existing one. More generally, every situation where objects are being dynamically created require the use of classes.
I've read a lot of tutorials and the book "Javascript : the good parts", but yet it seems to me that there is no way to define classes that respect 1) encapsulation and 2) efficient member methods declaration (I mean : member methods that are being defined once, and shared among every class instances).
To define private variables, closures are being used :
function ClassA()
{
var value = 1;
this.getValue = function()
{
return value;
}
}
The problem here is that every instance of "ClassA" will have its own copy of the member function "getValue", which is not efficient.
To define member functions efficiently, prototype is being used :
function ClassB()
{
this.value = 1;
}
ClassB.prototype.getValue = function()
{
return this.value;
}
The problem here is that the member variable "value" is public.
I don't think that this issue can be solved easily, since "private" variables need to be defined DURING object creation (so that the object can have access to its context of creation, without exposing thoses values) whereas prototype-based member functions definition has to be done AFTER object creation, so that prototype makes sense ("this.prototype" does not exists, I've checked).
Or am I missing something ?
EDIT :
First of all, thank you for your interesting answers.
I just wanted to add a little precision to my initial message :
What I really want to do is to have 1) private variables (encapsulation is good, because people only have access to what they need) and 2) efficient member methods declaration (avoid copies).
It seems that simple private variables declaration can really only be achieved via closure in javascript, that's essentially why I focused on the class based approach. If there is a way to achieve simple private variables declaration with a prototype based approach, that's okay for me, I'm not a fierce class-based approach proponnent.
After reading the answers, it seems like the simple solution is to forget about privates, and use a special coding conventions to detter other programmers from accessing "private" variables directly...
And I agree, my title / first sentence was misleading regarding the issue I wanted to discuss here.
Shh, come here! Wanna hear a secret?
Classical inheritance is a tested and tried approach.
It is useful to implement it in JavaScript often. Classes are a nice concept to have and having templates for modeling our world after objects is awesome.
Classical inheritance is just a pattern. It's perfectly OK to implement classical inheritance in JavaScript if it's the pattern you need for your use case.
Prototypical inheritance focuses on sharing functionality and that's awesome (dinasaur drumstick awesome), but in some cases you want to share a data-scheme and not functionality. That's a problem prototypical inheritance does not address at all.
So, you're telling me classes are not evil like everyone keeps telling me?
No, they are not. What the JS community frowns upon is not the concept of classes, it's limiting yourself to just classes for code reuse. Just like the language does not enforce strong or static typing, it doesn't enforce schemes on object structure.
In fact, behind the scene clever implementations of the language can turn your normal objects to something resembling classical inheritance classes.
So, how do classes work in JavaScript
Well, you really only need a constructor:
function getVehicle(engine){
return { engine : engine };
}
var v = getVehicle("V6");
v.engine;//v6
We now have a vehicle class. We didn't need to define a Vehicle class explicitly using a special keyword. Now, some people don't like to do things this way and are used to the more classical way. For this JS provides (silly imho) syntactic sugar by doing:
function Vehicle(engine){
this.engine = engine;
}
var v = new Vehicle("V6");
v.engine;//v6
That's the same thing as the example above for the most part.
So, what are we still missing?
Inheritance and private members.
What if I told you basic subtyping is very simple in JavaScript?
JavaScript's notion of typing is different than what we're used to in other languages. What does it mean to be a sub-type of some type in JS?
var a = {x:5};
var b = {x:3,y:3};
Is the type of b a sub type of the type of a? Let's say if it is according to (strong) behavioral subtyping (the LSP):
<<<< Begin technical part
Contravariance of method arguments in the subtype - Is fully preserved in this sort of inheritance.
Covariance of return types in the subtype - Is fully preserved in this sort of inheritance.
No new exceptions should be thrown by methods of the subtype, except where those exceptions are themselves subtypes of exceptions thrown by the methods of the supertype. - Is fully preserved in this sort of inheritance.
Also,
Preconditions cannot be strengthened in a subtype.
Postconditions cannot be weakened in a subtype.
Invariants of the supertype must be preserved in a subtype.
The history rule
All of these are again, are up to us to keep. We can keep them as tightly or loosly as we want, we don't have to, but we surely can.
So matter of fact, as long as we abide to these rules above when implementing our inheritance, we're fully implementing strong behavioral subtyping, which is a very powerful form of subtyping (see note*).
>>>>> End technical part
Trivially, one can also see that structural subtyping holds.
How would this apply to our Car example?
function getCar(typeOfCar){
var v = getVehicle("CarEngine");
v.typeOfCar = typeOfCar;
return v;
}
v = getCar("Honda");
v.typeOfCar;//Honda;
v.engine;//CarEngine
Not too hard, was it? What about private members?
function getVehicle(engine){
var secret = "Hello"
return {
engine : engine,
getSecret : function() {
return secret;
}
};
}
See, secret is a closure variable. It's perfectly "private", it works differently than privates in languages like Java, but it's impossible to access from the outside.
What about having privates in functions?
Ah! That's a great question.
If we want to use a private variable in a function we share on the prototype we need to firrst understand how JS closures and functions work.
In JavaScript functions are first class. This means you can pass functions around.
function getPerson(name){
var greeting = "Hello " + name;
return {
greet : function() {
return greeting;
}
};
}
var a = getPerson("thomasc");
a.greet(); //Hello thomasc
So far so good, but we can pass that function bounded to a around to other objects! This lets you do very loose decoupling which is awesome.
var b = a.greet;
b(); //Hello thomasc
Wait! How did b know the person's name is thomasc? That's just the magic of closures. Pretty awesome huh?
You might be worried about performance. Let me tell you how I learned to stop worrying and started to love the optimizing JIT.
In practice, having copies of functions like that is not a big issue. Functions in javascript are all about well, functionality! Closures are an awesome concept, once you grasp and master them you see it's well worth it, and the performance hit really isn't that meaningful. JS is getting faster every day, don't worry about these sort of performance issues.
If you think it's complicated, the following is also very legitimate. A common contract with other developers simply says "If my variable starts with _ don't touch it, we are both consenting adults". This would look something like:
function getPerson(name){
var greeter = {
greet : function() {
return "Hello" +greeter._name;
}
};
greeter._name = name;
return greeter;
}
Or in classical style
function Person(name){
this._name = name;
this.greet = function(){
return "Hello "+this._name;
}
}
Or if you'd like to cache the function on the prototype instead of instantiate copies:
function Person(name){
this._name = name;
}
Person.prototype.greet = function(){
return "Hello "+this._name;
}
So, to sum it up:
You can use classical inheritance patterns, they are useful for sharing types of data
You should also use prototypical inheritance, it is just as potent, and much more in cases you want to share functionality.
TheifMaster pretty much nailed it. Having privates private is really not a big deal as one might think in JavaScript, as long as your code defines a clear interface this should not be problematic at all. We're all concenting adults here :)
*The clever reader might think: Huh? Weren't you tricking me there with the history rule? I mean, property access isn't encapsulated.
I say no, I was not. Even if you don't explicitly encapsulate the fields as private, you can simply define your contract in a way that does not access them. Often like TheifMaster suggested with _. Also, I think the history rule is not that big of a deal in a lot of such scenarios as long as we're not changing the way property access treats properties of the parent object. Again, it's up to us.
I don't want to be discouraging since you seem to be a fairly new member of StackOverflow, however I'm going to have to be a little in your face and say that it's a really bad idea to try to implement classical inheritance in JavaScript.
Note: When I say that it's a bad idea to implement classical inheritance in JavaScript I mean that trying to simulate actual classes, interfaces, access modifiers, etc. in JavaScript is a bad idea. Nevertheless, classical inheritance as a design pattern in JavaScript is useful as it's just syntactic sugar for prototypal inheritance (e.g. maximally minimal classes). I use this design pattern in my code all the time (a la augment).
JavaScript is a prototypal object-oriented programming language. Not a classical object-oriented programming language. Sure, you can implement classical inheritance on top of JavaScript but before you do keep the following things in mind:
You're going against the spirit of the language, which means that you'll be faced with problems. Lots of problems - performance, readability, maintainability, etc.
You don't need classes. Thomas, I know that you truly believe that you need classes but trust me on this. You don't.
For your sake I'll provide two answers to this question. The first one will show you how to do classical inheritance in JavaScript. The second one (which I recommend) will teach you to embrace prototypal inheritance.
Classical Inheritance in JavaScript
Most programmers start with trying to implement classical inheritance in JavaScript. Even JavaScript Gurus like Douglas Crockford tried to implement classical inheritance in JavaScript. I too tried to implement classical inheritance in JavaScript.
First I created a library called Clockwork and then augment. However I wouldn't recommend you to use either of these libraries because they go against the spirit of JavaScript. The truth is that I was still an amateur JavaScript programmer when I wrote these classical inheritance libraries.
The only reason I mention this is because everyone is an amateur at some point of time, and although I would prefer that you didn't use classical inheritance patterns in JavaScript, I can't expect you to understand why prototypal inheritance matters just yet.
You can't learn how to cycle without falling down a few times. I believe you're still in the learning phase with respect to prototypal inheritance. Your need for classical inheritance is like the training wheels on cycles.
Nevertheless, training wheels are important. If you want there are some classical inheritance libraries out there which should make you more comfortable writing code in JavaScript. One such library is jTypes. Just remember to take off the training wheels when you are confident of your skills as a JavaScript programmer.
Note: Personally I don't like jTypes one bit.
Prototypal Inheritance in JavaScript
I'm writing this section as a milestone for you so that you can come back later and know what to do next when you are ready to learn about true prototypal inheritance.
First of all the following line is wrong:
The javascript prototype-based object-oriented programming style is interesting, but there are a lot of situations where you need the ability to create objects from a class.
This is wrong because:
You will never need to create objects from a class in JavaScript.
There is no way to create a class in JavaScript.
Yes it's possible to simulate classical inheritance in JavaScript. However you're still inheriting properties from objects and not classes. For example, ECMAScript Harmony classes are just syntactic sugar for the classical pattern of prototypal inheritance.
In the same context the example you gave is also wrong:
For instance in a vector drawing application, the workspace will usually be empty at the beginning of the drawing : I cannot create a new "line" from an existing one. More generally, every situation where objects are being dynamically created require the use of classes.
Yes you can create a new line from an existing one even though the workspace is empty in the beginning. What you need to understand is that the line is not actually drawn though.
var line = {
x1: 0,
y1: 0,
x2: 0,
y2: 0,
draw: function () {
// drawing logic
},
create: function (x1, y1, x2, y2) {
var line = Object.create(this);
line.x1 = x1;
line.y1 = y1;
line.x2 = x2;
line.y2 = y2;
return line;
}
};
Now you can draw your the above line by simply calling line.draw or else you could create a new line from it:
var line2 = line.create(0, 0, 0, 100);
var line3 = line.create(0, 100, 100, 100);
var line4 = line.create(100, 100, 100, 0);
var line5 = line.create(100, 0, 0, 0);
line2.draw();
line3.draw();
line4.draw();
line5.draw();
The lines line2, line3, line4 and line5 form a 100x100 square when drawn.
Conclusion
So you see you really don't need classes in JavaScript. Objects are enough. Encapsulation can be easily achieved using functions.
That being said you can't have public functions of each instance access the private state of the object without each instance having its own set of public functions.
This is not a problem however because:
You don't really need private state. You may think that you do, but you really don't.
If you really want to make a variable private then as ThiefMaster mentioned just prefix the variable name with an underscore and tell your users not to mess with it.
Aight, here's my attempt at solving this particular issue, although I think following conventions it's a better approach, ie. prefix your variables with _. Here I just keep track of the instances in an array, they can then be removed with a _destroy method. I'm sure this can be improved but hopefully it will give you some ideas:
var Class = (function ClassModule() {
var private = []; // array of objects of private variables
function Class(value) {
this._init();
this._set('value', value);
}
Class.prototype = {
// create new instance
_init: function() {
this.instance = private.length;
private.push({ instance: this.instance });
},
// get private variable
_get: function(prop) {
return private[this.instance][prop];
},
// set private variable
_set: function(prop, value) {
return private[this.instance][prop] = value;
},
// remove private variables
_destroy: function() {
delete private[this.instance];
},
getValue: function() {
return this._get('value');
}
};
return Class;
}());
var a = new Class('foo');
var b = new Class('baz');
console.log(a.getValue()); //=> foo
console.log(b.getValue()); //=> baz
a._destroy();
console.log(b.getValue()); //=> baz
You don't need private/public at runtime. These are enforceable statically. Any project complex enough to enforce private properties are not used outside will have a build/pre-process step, which you can use
to verify the fact. Even languages with syntax for private/public have a way to access private at runtime.
As for defining class-based objects, the constructor+prototype you are using is the simplest and most efficient way. Any kind of additional wizardry will
be more complex and less performant.
Although you can cache prototype so you don't have to repeat ClassB.prototype. all the time:
//in node.js you can leave the wrapper function out
var ClassB = (function() {
var method = ClassB.prototype;
function ClassB( value ) {
this._value = value;
}
method.getValue = function() {
return this._value;
};
method.setValue = function( value ) {
this._value = value;
};
return ClassB;
})();
The above does not require any library and you can easily create a macro for it.
Also, in this case even a regex is enough to verify
that "private" properties are used correctly. Run /([a-zA-Z$_-][a-zA-Z0-9$_-]*)\._.+/g through the file and see that the first match
is always this. http://jsfiddle.net/7gumy/
It's impossible as far as I know without other instances influencing the value, so if it's a constant you're still good by wrapping it in a function like this:
(function( context ) {
'use strict';
var SOME_CONSTANT = 'Hello World';
var SomeObject = function() {};
SomeObject.prototype.sayHello = function() {
console.log(SOME_CONSTANT);
};
context.SomeObject = SomeObject;
})( this );
var someInstance = new SomeObject();
someInstance.sayHello();
The best you could do is annotate that a property shouldn't be touched by using an underscore like this._value instead of this.value.
Note that private functions are possible by hiding them in a function:
(function( context ) {
'use strict';
var SomeObject = function() {};
var getMessage = function() {
return 'Hello World';
};
SomeObject.prototype.sayHello = function() {
console.log(getMessage());
};
context.SomeObject = SomeObject;
})( this );
var someInstance = new SomeObject();
someInstance.sayHello();
Here is an example of 2 'Classes' extending and interacting with each other: http://jsfiddle.net/TV3H3/
If you really want private entities on a per instance basis, but still want to inherit your methods, you could use the following set-up:
var Bundle = (function(){
var local = {}, constructor = function(){
if ( this instanceof constructor ) {
local[(this.id = constructor.id++)] = {
data: 123
};
}
};
constructor.id = 0;
constructor.prototype.exampleMethod = function(){
return local[this.id].data;
}
return constructor;
})();
Now if you create a new Bundle, the data value is locked away inside:
var a = new Bundle(); console.log( a.exampleMethod() ); /// 123
However you now get into the debate as to whether you should truly have private values in JavaScript. As far as I've found it's always better for those that may need to extend your code—even yourself—to have open access to everything.
There are also hidden downsides to the above pattern, besides not being so readable, or being clunky to access "private" values. One fact is that every single instance of Bundle will retain a reference to the local object. This could mean—for example—if you created thousands of Bundles, and deleted all but one of them, the data held in local would not be garbage collected for all Bundles ever created. You'd have to include some deconstruction code to fix that... basically making things more complicated.
So I'd recommend dropping the idea of private entities / properties, whichever pattern you decide to go for... object-based or constructor. The benefit of JavaScript is that all these different approaches are possible—it's no-where-near as clear cut as class-based languages—which some could argue makes things confusing, but I like the freedom JavaScript lends towards being quick and expressive.
with regards this statement in your question:
For instance in a vector drawing application, the workspace will usually be empty at the beginning of the drawing : I cannot create a new "line" from an existing one. More generally, every situation where objects are being dynamically created require the use of classes.
You seem to be under the misunderstanding that objects in Javascript can only be made by cloning existing objects, which would backtrack to the problem of "okay but what about the very first object? that can't be made by cloning an existing object because there aren't any existing objects."
However you can make objects from scratch, and the syntax for that is as simple as var object = {}
I mean, that's the simplest possible object, an empty object. More useful of course would be an object with stuff in it:
var object = {
name: "Thing",
value: 0,
method: function() {
return true;
}
}
and so on, and now you're off to the races!
There are cleverer people than I answering this question, but I wanted to note one part in particular that you just edited in - the private variable part.
You can simulate this using closures; an awesome construct which allows a function to have it's own environment. You could do this:
var line = (function() {
var length = 0;
return {
setLen : function (newLen) {
length = newLen;
},
getLen : function () {
return length;
}
};
}());
This will set line to be an object with the setLen and getLen methods, but you'll have no way of manually accessing length without using those methods.
ap = Array.prototype,
aps = ap.slice,
apsp = ap.splice,
I often see code like above in different frameworks. What are the benefits of this?
Why not use it directly?
When used exactly as you've shown, the primary reason is to reduce the amount of typing in code that will heavily utilize the referenced method or object. Further, this can have the effect of reducing the overall size of a script. Consider:
Array.prototype.someFunction1 = function () { /*someFunction1 */ };
Array.prototype.someFunction2 = function () { /*someFunction2 */ };
Array.prototype.someFunction3 = function () { /*someFunction3 */ };
Array.prototype.someFunction4 = function () { /*someFunction4 */ };
... (284 characters) versus:
var ap = Array.prototype;
ap.someFunction1 = function () { /*someFunction1 */ };
ap.someFunction2 = function () { /*someFunction2 */ };
ap.someFunction3 = function () { /*someFunction3 */ };
ap.someFunction4 = function () { /*someFunction4 */ };
... which has 261 characters. Trivial, yes, but on a large scale this can make enough of a difference to be worthwhile in distributed code (think Google-hosted jQuery).
Sometimes, however, this is done to preserve scope through a closure:
var self = this;
this.someProperty = 5;
var myDiv = document.createElement('div');
myDiv.addEventListener('mousedown', function(e) { alert(self.someProperty); }, false);
Several benefits:
Faster at run-time (fewer lookups to get the final result)
Smaller code before minification
Easier to reduce even more with minification
Less typing when coding
One should note that I think it makes the code less readable to people not already familiar with the code or its conventions because the code isn't as self documenting. Everyone knows what Array.prototype.splice is but strangers don't know what aps is until they study the code, track down its definition and remember what it is.
I was asked in a comment to explain the fewer lookups issue:
For the interpreter to resolve Array.prototype.splice, it has to do the following:
Look in the local scope for the Array name. It doesn't find it.
Look in any closures (e.g. parent scope) for the Array name. It doesn't find it.
Look in the global scope for the Array name. It finds it.
On the Array object, look for the prototype property.
On the prototype property, look for the splice property and now it finally has the function it needs.
For the interpreter to resolve aps, it has to do this:
Look in the local scope for the aps name. It finds it and not it has the function it needs.
The pre-assignment to aps has essentially pre-done the lookups so that they are already resolved at runtime. This removes some flexibility because if the value of the splice or prototype properties are changed, the variable aps won't reflect that change, but if you know they aren't supposed to change (something the run-time interpreter doesn't know), then you can take advantage of this shortcut.
One functional reason this pattern would exist would be to protect against other javascript code changing the meaning of the particular methods. Essentially protecting from code like the following
Array.prototype.splice = function() {
// This is evil
};
The other more likely though is the developer simply didn't want to type Array.prototype.splice and prefered a shorter version like apsp.
There are two benefits.
a is easier to minify then Array.prototype.slice
a is a single lookup where Array.prototype.slice is multiple look ups
So basically they are both micro optimisations. Which are valuable in libraries because libraries care about being as efficient as possible
I recently found out that Javascript function can have classes, so I was wondering if OOP is also possible through javascript. Is It? If yes, Could you please point out some tutorials or site, where I can start with?
OOP is definitely possible. While Javascript doesn't have "classes" like most OO languages do, what it does have is called "prototypes". Basically, objects are defined in terms of other objects rather than classes. (Objects can also emulate classes to some degree, for those who can't wrap their minds around prototypal inheritance.)
One could argue JS's OO capabilities exceed those of most languages, considering objects play an even more essential role than in languages with classes.
OOP is central to Javascript, but it's not classical OOP. Javascript uses prototypes, not classes.
Douglas Crockford is a Javascript genius, so his Prototypal Inheritance in Javascript is a nice starting point. A Google search for "Javascript OOP" likely will turn up some neat articles to peruse, as well — I like the article by Mike Koss.
Javascript is an intrinsically OOP language. Like others have said, it is classless, but you have a choice of how you want to create objects.
You can create objects that make use of different types of inheritance.
A pseudo-classical inheritance. Here you build constructor functions and use new to create classes. This will look most like the typical class based OOP.
Prototypal inheritance. - This is what many of the other answer referred to.
Functional inheritance. - In this mode you make use of closures, anonymous functions, and strategic returns to create truly private and protected variables.
There's a fair amount of cross over among these types. Suffice it to say that Javascript is a very flexible and powerful language for OOP.
I'm just learning about OOP in JS as well. Here is an example of functional inheritance I put together:
jsFiddle
// Object constructor
var parent = function (initial) {
var that, privateNumber, hiddenVar;
that = {};
// Public variables
that.share = initial - 32;
// Public methods
that.getNumber = function () {
return privateNumber;
};
// Private properties
privateNumber = initial;
hiddenVar = "haha can't get me";
return that;
};
// Second object constructor that inherits from parent
var child = function (initial) {
var that, privateName;
// Inherit from parent
that = parent(initial);
// Public methods
that.getName = function () {
return privateName;
};
// Private poroperties
privateName = "Ludwig the " + initial + "th";
return that;
};
// Create objects
var newPar1 = parent(42);
var newPar2 = parent(10);
var newChild1 = child(0);
var newChild2 = child(100);
// Output on the jsFiddle page refed above: http://jsfiddle.net/ghMA6/
http://msdn.microsoft.com/en-us/magazine/cc163419.aspx
http://www.dustindiaz.com/namespace-your-javascript/
http://vimeo.com/9998565
frameworks for oop js
http://jsclass.jcoglan.com/
http://www.prototypejs.org/
Pluralsight - JavaScript for C# Developers - Shawn Wildermuth - 2h 5m
JavaScript Basics
JavaScript Functions
Object-Oriented JavaScript
Practical Application
and
Object-Oriented JavaScript: Create scalable, reusable high-quality JavaScript applications and libraries - 356 pages -2008 -packed publishing
Yes. It is possible. I have ever using the Script# to build javascript application, It allow you writing C# code, and translate to JavaScript.
it is an good experience, especially for large project, it will force your thinking in the OOP way to order your code.
The tool can be found at: (it is open source but write by an Microsoft employee)
http://scriptsharp.com
If you are not familiar with C# you can also find the similar tool for writing javascript in Java.
And if you don't want to using those too, you can investigate how it convert the code to understand how it implement the OOP feature.
Here is an example of accomplishing an OO structure in javascript that is utilizing a library(not required, recommended)
//Create and define Global NameSpace Object
( function(GlobalObject, $, undefined)
{
GlobalObject.PublicMethod = function()
{
///<summary></summary>
}
GlobalObject.Functionality = {}
}) (GlobalObject = GlobalObject || {}, jQuery);
//New object for specific functionality
( function(Events, $, undefined)
{
//Member Variables
var Variable; // (Used for) , (type)
// Initialize
Events.Init = function()
{
///<summary></summary>
}
// public method
Events.PublicMethod = function(oParam)
{
///<summary></summary>
///<param type=""></param>
}
// protected method (typically define in global object, but can be made available from here)
GlobalObject.Functionality.ProtectedMethod = function()
{
///<summary></summary>
}
// internal method (typically define in global object, but can be made available from here)
GlobalObject.InternalMethod = function()
{
///<summary></summary>
}
// private method
var privateMethod = function()
{
///<summary></summary>
}
Events.PublicProperty = "Howdy Universe";
}) (GlobalObject.Functionality.Events = GlobalObject.Funcitonality.Events || {}, jQuery )
// Reusable "class" object
var oMultiInstanceClass = function()
{
// Memeber Variables again
var oMember = null; //
// Public method
this.Init = function(oParam)
{
oMember = oParam;
}
}
The strength to this is that it initializes the Global object automatically, allows you to maintain the integrity of your code, and organizes each piece of functionality into a specific grouping by your definition.
This structure is solid, presenting all of the basic syntactical things you would expect from OOP without the key words.
There are even some ingenious ways to set up interfaces as well. If you choose to go that far, a simple search will give you some good tutorials and tips.
Even setting up intellisense is possible with javascript and visual studio, and then defining each piece and referencing them makes writing javascript cleaner and more manageable.
Using these three methods as needed by your situation helps keep the global namespace clean, keep your code organized and maintains separation of concerns for each object.. if used correctly. Remember, Object Oriented Design is of no use if you don't utilize the logic behind using objects!
I have been trying to learn how to add testing to existing code -- currently reading reading Working Effectively With Legacy Code. I have been trying to apply some of the principles in JavaScript, and now I'm trying to extract an interface.
In searching for creating interfaces in JavaScript, I can't find a lot -- and what I find about inheritance seems like their are several different ways. (Some people create their own base classes to provide helpful methods to make it easier to do inheritance, some use functions, some use prototypes).
What's the right way? Got a simple example for extracting an interface in JavaScript?
There's no definitive right way, because so many people are doing so many different things.. There are many useful patterns.
Crockford suggests that you "go with the grain", or write javascript in a way that corresponds to javascript's prototypal nature.
Of course, he goes on to show that the original model that Netscape suggested is actually broken. He labels it "pseudoclassical", and points out a lot of the misdirection and unnecessary complexity that is involved in following that model.
He wrote the "object" function as a remedy (now known as Object.create() ). It allows for some very powerful prototypal patterns.
It's not always easy to do develop a clean interface when you have to work with legacy javascript, especially not when you're dealing with large systems, usually including multiple libraries, and each implementing a unique style and different inheritance pattern. In general, I'd say that the "right way" to do inheritance is the one which allows you to write a clean interface which behaves well in the context of your legacy code, but also allows you to refactor and eliminate old dependencies over time.
Considering the differences between the major library patterns, I've found that the most successful route to take in my own work is to keep my interfaces independent of the library interfaces entirely. I'll use a library or module if it's helpful, but won't be bound to it. This has allowed me to refactor a lot of code, phase out some libraries, and use libraries as scaffolding which can be optimized later.
Along these lines, I've written interfaces that were inspired by Crockford's parasitic inheritance pattern. It's really a win for simplicity.
On the other side of the coin, I'm sure you could argue for picking a library, enforcing it across your team, and conforming to both its inheritance patterns and its interface conventions.
There are no class in javascript, only objects.
But if you insist on emulating the class based object-oriented model you can use this:
function ChildClass() {
ParentClass.call(this);
// Write the rest of your constructor function after this point.
};
ChildClass.prototype = jQuery.extend({}, ParentClass.prototype, ChildClass.prototype);
jQuery.extend is a 'shallow copy' function from the jQuery library. You can replace it with any other object copying/cloning function.
You are looking at two different things.
First you have interfaces. The most accepted way of implementing this is though Duck Typing ("if it looks like a duck and quacks like a duck then it is a duck"). This means that if an object implements a set of methods of the interface then it is that interface. You implement this by having an array of method names that define an interface. Then to check if an object implements that interfece you see if it implements those methods. Here is a code example I whipped up:
function Implements(obj, inter)
{
var len = inter.length, i = 0;
for (; i < len; ++i)
{
if (!obj[inter[i]])
return false;
}
return true;
}
var IUser = ["LoadUser", "SaveUser"];
var user = {
LoadUser : function()
{
alert("Load");
},
SaveUser : function()
{
alert("Save");
}
};
var notUser = {
LoadUser : function()
{
alert("Load");
}
};
alert(Implements(user, IUser));
alert(Implements(notUser, IUser));
Now you have inheritance. JS has no inheritance built in; so you have to implement it manually. This is just a matter of "copying" the properties of one object to another. Here is another code sample (not perfect but it demonstrates the point):
function InheritObject(base, obj)
{
for (name in base)
{
if (!obj[name])
obj[name] = base[name];
}
}
var Base = {
BaseFunc : function() { alert("BaseFunc from base"); },
InheritFunc : function() { alert("InheritFunc from base"); }
}
var Inherit = {
InheritFunc : function() { alert("InheritFunc from inherit"); },
AnotherFunc : function() { alert("AnotherFunc from inherit"); }
}
InheritObject(Base, Inherit);
Inherit.InheritFunc();
Inherit.BaseFunc();
Inherit.AnotherFunc();
Base.BaseFunc();
Base.InheritFunc();
You probably want to look at http://www.mootools.net. It has my favorite implementation of Classes. You also definitely want to check out "Pro Javascript Design Patterns"
http://www.amazon.com/JavaScript-Design-Patterns-Recipes-Problem-Solution/dp/159059908X
This book goes into good detail about how to emulate OOP in javascript.
Also check out Dean Edwards' Base.js. You can have a look at it here, the blog post is self-explanatory.
Prototype offers its own take on inheritance, from http://www.prototypejs.org/api/class/create:
var Animal = Class.create({
initialize: function(name, sound) {
this.name = name;
this.sound = sound;
},
speak: function() {
alert(this.name + " says: " + this.sound + "!");
}
});
// subclassing Animal
var Snake = Class.create(Animal, {
initialize: function($super, name) {
$super(name, 'hissssssssss');
}
});