I'm building a library (https://github.com/OscarGodson/storageLocker), a localStorage wrapper to be more exact, but because this is my first try at OO JavaScript I'm still learning and I have a couple questions.
I've seen in other libraries that sometimes they wrap them in a anonymous function. Do I, or should I, do that with this? And if so, how without breaking anything?
For the internal API (basically, the internal functions) how should I write them? Should add them to the main object e.g. storageLocker.prototype.myInternalFunction() or just myInternalFunction() randomly in my script? I didn't want the functions to be global though... One of the functions for example just checks a bunch of items in the JSON, sees if their objects, and then checks what the object type is (like Date()) and then converts it.
How/where should I add global, to my script, vars? e.g. i have a var called patterns that is something like var patterns = {"date":/\/Date\(([0-9]+)\)\//} how should I add that into my script?
Thanks a lot. I want to write my script the right way so im asking you guys. I don't know of any JS guys locally that do any OO JS, they're all old school types...
I'd say:
1) the purpose of this technique is not pollute the global namespace. That is a good thing.
In the example below you can see that all your interaction with the library is via one object MyLibrary. Public API is the return value of the anonymous function.
var MyLibrary = function() {
// private
this.InternalVariable = 'some value';
function internalFunction(x,y) {
return x + y;
}
function getInternalVariable() {
return this.InternalVariable;
}
// public
return {
publicVariable : '1.0',
publicFunction : function(x,y) {
return x + y
},
accessInternalVariable : function() {
return getInternalVariable();
}
}
}();
2) see also the example above on how to place your "internal" functions
3) if you global variable is some kind of a configuration option, I'd just make public setter/getter and kept the variable "private"
http://nefariousdesigns.co.uk/archive/2010/10/object-oriented-javascript-follow-up-part-2-technical/
has a decent section on namespacing worth reading.
http://yuiblog.com/blog/2007/06/12/module-pattern/
is also another good overview.
For more great material on good javascript practices, check out
http://javascript.crockford.com/
After our discussion in the comments, I've changed the example to this:
var storageLocker = function (selector) {
var _selector = selector || "default value";
function myPrivateFunction() {
}
var public = {
get: function () {
return _selector;
},
uppercase : function () {
_selector = _selector.toUpperCase()
return this;
}
}
return public;
};
// use:
var test = storageLocker("search for this").uppercase().get();;
alert(test);
While this isn't exactly an example of a library/module (because you're accessing the code by calling the constructor directly), it is an example of keeping the same object in scope for further chaining of methods. Actually it's not returning the storageLocker object, it's returning the 'public' object, but that object has access to the storageLocker's scope through closure.
There could be other better ways to do this by perhaps returning the storageLocker object itself, but that would require a bit more thinking through.
Related
Just see the code and tell me what kind of Javascript approach is it?
var Arithmetic = function(){
var obj = {
add: function(a,b) { return a + b; },
multiply: function(a,b) { return a * b; }
};
return obj;
}();
var resultAdd = Arithmetic.add(a,b);
var resultMul = Arithmetic.multiply(a,b);
Why people write the js code in this way....any advantage is there for writing such way.
The above code is related to any design pattern? If yes then tell me the name.
I always write the code like this way and it is easy to understand.
function add(a,b)
{
return a+b;
}
function multiply(a,b)
{
return a*b;
}
and i just call it like this way
var x=add(2,3);
var y=multiply(5,8);
also tell me what is the disadvantage of writing code my way.
The disadvantage to writing code your way is that you put lots of stuff in the global namespace. Imagine what happens when you add your code that defines the add and multiply methods that work on numbers and then include a library that deals with Vectors which also defines the add and multiply methods, but which work on vectors. The methods defined last will overwrite the ones previously defined, breaking some of the code that relies on them.
For this reason, it is preferable to not pollute the global scope and when you have functionality you wish to make available, make it available via a namespace (Arithmetic.add() instead of add()).
If you analize the code a bit, var obj is defined not in the global scope, but in the scope of an anonymous function, so code outside of it can use the obj name for a variable without clashing. The functionality (two methods) is exported to public use by returning an object with the two properties from the anonymous function. Since there is no need for more than one instance of the two methods, the anonymous function returns immediately (http://en.wikipedia.org/wiki/Immediately-invoked_function_expression).
Another advantage to this pattern is that it allows to have private variables:
var uniqueId = function() {
var id = 0;
return function() { return id++; }
}();
uniqueId(); // 0
uniqueId(); // 1
In the example above there is no way to accidentally corrupt the uniqueId function to give bad (non-unique) results because you expose just the functional interface you want, instead of the whole mechanism.
Consider the equivalent in your style:
var id = 0;
function uniqueId() { return id++; };
uniqueId(); // 0
id = 0;
uniqueId(); // 0
The code you gave us is an advanced example of Object Oriented code. I don'r really see the advantage of that encapuslated obj right now, that just makes things difficult to read.
Basically Arithmetic acts as a static class. Without that encapsulated obj and the self-executing function, it may be written like that:
var Arithmetic = {
add: function(a,b) { return a + b; },
multiply: function(a,b) { return a * b; }
}
The code you gave us really does the same - it just doesn't write down that object directly but creates it using that self-executing function (that is a closure, a "function without name", that is called (by adding () to it) immediately after it is created).
The advantage of OO code is not really easy to bring down in a few lines, but regarding to static classes as a collection of methods (as it's done here): it's encapusulation.You can treat each class/object you create as a blackbox and don't have to worry about the details (once it works of course).
The disadvantqage of your "traditional" approach is: It get's corweded once you got many, many functions, and you cannot easily tell which "group" they belong to unless you include thst in your naming conventions (like math_add() or math_mul())
I've been wondering for a while - what can JavaScript closures be used for?
I know how to write them and I know how they work, but I just can't get the idea of how they can be used.
function closure() {
var name = "John";
function displayName() {
return 'Hello, ' + name;
}
return displayName;
}
So far I only found one use for them - encapsulating data, so it won't be visible outside the function.
But what else can they be used for? Should I write OOP with closures? Do I need to put all my code inside a closure so it wont mess the global scope?
Any clarifications are highly appreciated!
Can also be used to protect your code inside the colsure against naming conflicts between different libraries outside the closure. Ex whenever I create a JQuery plugin I create it as a self calling closure where I pass In "JQuery", but can safely refer to $ inside the closure because of the local scope of the named $ variable in my function definition. Even if there are other libraries using the $ variable for a different purpose
(function($){ //use $ safely inside the closure })
(jQuery);
Personally, besides obvious things like encapsulating or creating private contexts, I like Singleton JavaScript Design Pattern:
function Singleton() {
// cached instance
var instance = this;
//proceed as normal - adding some variables
this.variable1 = 1000;
this.variable2 = 3000000;
Singleton = function() {
return instance;
}
}
var singleton1 = new Singleton();
var singleton2 = new Singleton();
if(singleton1 === singleton2) {
console.log("Singleton works :)");
}
else {
console.log("Singleton doesn't work :/");
}
You can paste this code directly into Chrome JavaScript console.
Of course you can tweak it to suit your needs. There is also some drawback - you can overwrite Singleton function, and you will not be able to access instance anymore. But this is another problem.
I found it a long time ago in JavaScript Patterns book by Stoyan Stefanov (O'Reilly)
. Check this out as there are other useful design patterns and examples of closures application. According to this book:
You can use closure to store some private data, which is accessible by the returned function but not to the outside code.
I'm trying to write fully automated unit tests in JavaScript and I'm looking for a way to read some private variables in various JS functions. I thought I recalled a way to inject privileged members into a function/object (and found an overwhelming occurrence of "no such thing as private in JS") and yet I can't find any resources indicating how.
I'm trying to read through the properties of .prototype but if there's a way, someone out here would know where to direct me faster than I'd find on my own.
Thanks
Update
Privileged means a function that is usable from outside an object and has access to read "private" variables (variables otherwise unable to read from outside). See http://javascript.crockford.com/private.html for Crockford's explanations.
A sample of the function I'm trying to inject to is o2, where I need to validate the value of x (this is a simplified example, the actual code does some transformations and sends them off to other functions which I plan on testing separately).
var o2 = function() {
var x = 'me';
};
Update 2:
Thanks to everyone who's taken the time to respond. I'm seeing that the overwhelming response here is, "private is private" despite the commentary I see in other SA questions where people say "nothing in JS is private". I guess that is more like rhetorical commentary rather than what I was hoping was some kind of insight into a potential loophole I didn't yet know about.
Correct answer to your question
Even if we try to help you as much as we can, the correct answer to your question is simple:
...you can't
What good would closure variables be if we could access them directly from outside of closure?
if you had an object with private variables, they wouldn't be accessible outside function closure, which is the constructor function.
var c = function() {
var priv = "private";
this.get = function() {
return priv;
};
}
var o = new c();
o.injected = function() {
return priv; // ERROR!!!!!! priv doesn't exist in function scope
};
It is of course different matter if you enclose the whole thing inside a function closure but then you wouldn't have object privates, but rather function closure internals that would be shared among all prototypes within this closure.
(function(){
var intrn = "internal";
// omit "var" to make it global
c = function() {
this.get = function() {
return intrn;
};
};
// omit "var" to make it global
o = new c();
o.injected = function() {
return intrn; // WORKS
};
})();
o.injected();
but this is different than object privates...
Know that I am quite late to the party, but yes it is possible. Although AFAIK it requires use of eval() and a helper method:
function foo(){
var a = 'a';
this.addMethod = function(prop, val){
this[prop] = eval('(' + val.toString() + ')');
}
}
var bar = new foo();
bar.b = 'b';
var Fn = function(){return a + this.b}
bar.addMethod('getValue', Fn);
bar.getValue(); //yields 'ab'
You can use eval() in this case to redefine the function within the context of the closure. However, using eval() is dangerous, ESPECIALLY don't eval() any user input, EVER. However, for use in a testing suite/script it should be fine.
I'd suggest you read Crockford's treatise on how to achieve privileged and private in javascript objects.
If by privileged, you mean methods that are not accessible outside the object, but are callable by other methods and are actually methods on the object, then there really isn't any way to do that because one you put a method on the object, javascript let's anyone call it.
If you just wanted to add a function that was only callable by methods, you could do that by having a private member variable (see how Crockford implements that) that was an object and you could put the methods on that object. Then all existing methods (implemented the way Crockford suggests in the constructor to have access to the private member data) could call those methods. They would technically be members of a different object, but could be given private access to your object's instance data if needed.
It's all pretty convoluted so you'd probably get a better answer if you described the problem you're really trying to solve.
I don't think you can do that. Consider the following code:
function foo() {
var privateVar = 10;
this.privilegedMethod = function() {
return privateVar;
}
}
var obj = new foo();
Here, privilegedMethod has access to privateVar, since it's part of the closure created when the method was defined. Of course, you can always attach a new method to the object after instantiation:
obj.newMethod = function() { return "hello" };
alert(obj.newMethod()); // alerts "hello"
But this new method won't have access to privateVar.
Using the Javascript module pattern, what are the advantages/dis-advantages of returning a bare object containing the interface, versus creating a named object containing the interface, then returning a reference? Example code below. I always put the interface into a named object, and the one advantage I see of this is I can do some debugging before I return it.
function bareObjectModule() {
return {
method1: function() {}
//etc.
}
}
function namedObjectModule() {
var namedObjectModule = {
method1: function() {}
}
//debug here?
return namedObjectModule;
}
The main advantage of returning the interface directly is that it is short and does not include much boilerplate but having a named reference is much more powerful and allows for other patterns that you could not originally. The biggest advantage is that it is much easier to have the functions reference each other if you have a reference to the module
var M = {};
M.f1 = function(){ ... };
M.f2 = function(){ M.f1() }; //functions can reference each other without
// a fragile dynamic binding through `this`
M.f3 = some_combinator(M.f2); //since you are not limited to defining things as
//property-value pairs you have much more flexibility..
return M;
Other than the debugging advantage you mentioned, i see no difference whatsoever in the 2 approaches. Since namedObjectModule is function local it'll anyway be discarded once the function returns (i.e. the variable name in the stack).
One minor point might be that with a named object, there will be a stack entry for the local variable 'namedObjectModule' (will be popped out once the function returns), and there will be an entry in the function call stack (to the same object) for the return to work. With bare object, the former can be avoided. Not sure if this has any real performance impact, unless you have thousands of objects in the stack.
The main difference is that with a referenced object you can use properties and call methods from other methods. You can't do that with a single object literal.
As an alternative to both approaches, you can call the enclosing function as a constructor (with new) and have it return this object to export the module.
var myModule = new function () {
this.methodA = function () { /* ... */ }
this.methodB = function () { /* ... */ }
console.log(this) // debug
}
No need to type return explicitly (constructors return this by default) and define an object literal (and come up with a name) as a bonus.
I've heard from a variety of places that global variables are inherently nasty and evil, but when doing some non-object oriented Javascript, I can't see how to avoid them. Say I have a function which generates a number using a complex algorithm using random numbers and stuff, but I need to keep using that particular number in some other function which is a callback or something and so can't be part of the same function.
If the originally generated number is a local variable, it won't be accessible from, there. If the functions were object methods, I could make the number a property but they're not and it seems somewhat overcomplicated to change the whole program structure to do this. Is a global variable really so bad?
I think your best bet here may be to define a single global-scoped variable, and dumping your variables there:
var MyApp = {}; // Globally scoped object
function foo(){
MyApp.color = 'green';
}
function bar(){
alert(MyApp.color); // Alerts 'green'
}
No one should yell at you for doing something like the above.
To make a variable calculated in function A visible in function B, you have three choices:
make it a global,
make it an object property, or
pass it as a parameter when calling B from A.
If your program is fairly small then globals are not so bad. Otherwise I would consider using the third method:
function A()
{
var rand_num = calculate_random_number();
B(rand_num);
}
function B(r)
{
use_rand_num(r);
}
Consider using namespaces:
(function() {
var local_var = 'foo';
global_var = 'bar'; // this.global_var and window.global_var also work
function local_function() {}
global_function = function() {};
})();
Both local_function and global_function have access to all local and global variables.
Edit: Another common pattern:
var ns = (function() {
// local stuff
function foo() {}
function bar() {}
function baz() {} // this one stays invisible
// stuff visible in namespace object
return {
foo : foo,
bar : bar
};
})();
The returned properties can now be accessed via the namespace object, e.g. ns.foo, while still retaining access to local definitions.
What you're looking for is technically known as currying.
function getMyCallback(randomValue)
{
return function(otherParam)
{
return randomValue * otherParam //or whatever it is you are doing.
}
}
var myCallback = getMyCallBack(getRand())
alert(myCallBack(1));
alert(myCallBack(2));
The above isn't exactly a curried function but it achieves the result of maintaining an existing value without adding variables to the global namespace or requiring some other object repository for it.
I found this to be extremely helpful in relation to the original question:
Return the value you wish to use in functionOne, then call functionOne within functionTwo, then place the result into a fresh var and reference this new var within functionTwo. This should enable you to use the var declared in functionOne, within functionTwo.
function functionOne() {
var variableThree = 3;
return variableThree;
}
function functionTwo() {
var variableOne = 1;
var var3 = functionOne();
var result = var3 - variableOne;
console.log(variableOne);
console.log(var3);
console.log('functional result: ' + result);
}
functionTwo();
If another function needs to use a variable you pass it to the function as an argument.
Also global variables are not inherently nasty and evil. As long as they are used properly there is no problem with them.
If there's a chance that you will reuse this code, then I would probably make the effort to go with an object-oriented perspective. Using the global namespace can be dangerous -- you run the risk of hard to find bugs due to variable names that get reused. Typically I start by using an object-oriented approach for anything more than a simple callback so that I don't have to do the re-write thing. Any time that you have a group of related functions in javascript, I think, it's a candidate for an object-oriented approach.
Another approach is one that I picked up from a Douglas Crockford forum post(http://bytes.com/topic/javascript/answers/512361-array-objects). Here it is...
Douglas Crockford wrote:
Jul 15 '06
"If you want to retrieve objects by id, then you should use an object, not an
array. Since functions are also objects, you could store the members in the
function itself."
function objFacility(id, name, adr, city, state, zip) {
return objFacility[id] = {
id: id,
name: name,
adr: adr,
city: city,
state: state,
zip: zip
}
}
objFacility('wlevine', 'Levine', '23 Skid Row', 'Springfield', 'Il', 10010);
"The object can be obtained with"
objFacility.wlevine
The objects properties are now accessable from within any other function.
I don't know specifics of your issue, but if the function needs the value then it can be a parameter passed through the call.
Globals are considered bad because globals state and multiple modifiers can create hard to follow code and strange errors. To many actors fiddling with something can create chaos.
You can completely control the execution of javascript functions (and pass variables between them) using custom jQuery events....I was told that this wasn't possible all over these forums, but I got something working that does exactly that (even using an ajax call).
Here's the answer (IMPORTANT: it's not the checked answer but rather the answer by me "Emile"):
How to get a variable returned across multiple functions - Javascript/jQuery