What kind of a pattern/object is this in Javascript? - javascript

I see this pattern a lot (which I actually use) but I want an explanation as to how it works.
var mystuff = function() {
var blah = function() {
};
return {
setup: function() {
blah();
};
};
}();
Then usage is very OOP like:
mystuff.setup();

What that's doing is returning a public interface to your object. It looks like you are using the public setup() function to access the private blah() function. This is one method of emulating public and private member functions in Javascript objects.
Since mystuff is defined with that trailing () at the bottom, it's executed immediately when the parser reaches mystuff.setup(), and actually returns an anonymous object (your public interface) with the setup() method.

Others have explained how it works. This is just somemore background info on the topic.
It's called the "Module pattern" (coined by Douglas Crockford I believe, but blogged about earlier).
It gives you three main benefits:
A namespace (the value to the left of "function")
A private "space" to put stuff in (vars, functions, etc) that don't need or should not pollute the global namespace (this is the stuff before the return statement)
A public "space" to put stuff that you want accessible to users of your namespace (this is the return statement)
all in a fairly readable form.

This is simply an example of nested functions in JavaScript. Although the method of calling them may seem "OOP-like" on the surface, this style very much belongs to the functional paradigm.
In essence, however, there's nothing too fancy going on. JavaScript is known as a language in which "everything is a function", which is close enough to the truth. All it means is that any function declared belongs strictly to its parent scope.

It's from a functional programming approach to object oriented programming. Local variables in the outer (anonymous) function (the constructor) are accessible to any function defined within the constructor, but not elsewhere, making the local variables private. Where it differs from the purely functional approach is that the constructor returns an object literal rather than another function. The local variables are accessible by inner functions due to what's termed a closure.
It's use is to create private fields & methods, in the form of local variables.

but I want an explanation as to how it works.
Let's desect it piece by piece.
function() { .... } is a syntax for anonymous function.
function() { .... }() is defining and calling the anonymous function on the same line.
The return value of the function in your sample is an object defined using JSON notation (Javscript Object Notation)
{ setup : .... } is an object with one attribute: it's called setup, and it happens to be a function, in your case.
so, mystuff got the return value, which is an object with a property (function) called setup, and mystuff.setup() invokes this setup function.
Now, the interesting part is probably how setup just calls the blah function, defined inside that enclosing anonymous function.
I believe the technical term here is closure (see the section forming closures) (Also see the wikipedia definition)
Essentially the function becomes like a module of its own, with variables bound to it.
It's explained in crescentfresh's answer

First of all, please avoid this syntax:
var mystuff=function(){...}();
It is bad coding practice since it isn't completely cross-browser as a few browsers will error here.
Get used to putting parentheses around the function like so:\
var mystuff=(function(){...})();
Nextly, regarding the pattern. This pattern is more commonly known as simply "encapsulation" in JavaScript. Closures is another possibly but more specifically it is purely encapsulation in this case.
Encapsulation simply means you are making some members private. What is private in this case? Well the blah variable is private in this case. Please get into the habit of proceeding private members with an underscore to indiciate they are private. It is good coding practice to distinguish public methods from private methods with an underscore.
<script type="text/javascript">
var obj=(function(){
//private members
var _p={};//toss all private members into a single object.
_p.list=[];
_p.init=function(){
_p.list=[];
};
//public members. use "this" to reference object followed by the method.
//however obj._p.list won't be accessible to the global scope
return {
reset:function()
{
_p.init();
}
,addName:function(str)
{
_p.list.push(''+str);//limit to strings
}
,getNames:function()
{
return _p.list.slice(0);//return a clone
}
,alertNames:function()
{
alert(this.getNames().join(","));
}
,getPrivateObj:function()
{
return _p;
}
};
})();
obj.alertNames();
obj.addName("Nandan");
obj.addName("Ram");
obj.alertNames();
obj.reset();
obj.alertNames();
obj.addName("Vinoth");
obj.addName("Kevin");
obj.alertNames();
alert(typeof obj._p);//undefined
var privateObj=obj.getPrivateObj();
alert(typeof privateObj);
alert(privateObj.list.join("|"));
</script>

Related

Are javascript IIFE's only about namespacing? [duplicate]

In javascript, when would you want to use this:
(function(){
//Bunch of code...
})();
over this:
//Bunch of code...
It's all about variable scoping. Variables declared in the self executing function are, by default, only available to code within the self executing function. This allows code to be written without concern of how variables are named in other blocks of JavaScript code.
For example, as mentioned in a comment by Alexander:
(function() {
var foo = 3;
console.log(foo);
})();
console.log(foo);
This will first log 3 and then throw an error on the next console.log because foo is not defined.
Simplistic. So very normal looking, its almost comforting:
var userName = "Sean";
console.log(name());
function name() {
return userName;
}
However, what if I include a really handy javascript library to my page that translates advanced characters into their base level representations?
Wait... what?
I mean, if someone types in a character with some kind of accent on it, but I only want 'English' characters A-Z in my program? Well... the Spanish 'ñ' and French 'é' characters can be translated into base characters of 'n' and 'e'.
So someone nice person has written a comprehensive character converter out there that I can include in my site... I include it.
One problem: it has a function in it called 'name' same as my function.
This is what's called a collision. We've got two functions declared in the same scope with the same name. We want to avoid this.
So we need to scope our code somehow.
The only way to scope code in javascript is to wrap it in a function:
function main() {
// We are now in our own sound-proofed room and the
// character-converter library's name() function can exist at the
// same time as ours.
var userName = "Sean";
console.log(name());
function name() {
return userName;
}
}
That might solve our problem. Everything is now enclosed and can only be accessed from within our opening and closing braces.
We have a function in a function... which is weird to look at, but totally legal.
Only one problem. Our code doesn't work.
Our userName variable is never echoed into the console!
We can solve this issue by adding a call to our function after our existing code block...
function main() {
// We are now in our own sound-proofed room and the
// character-converter libarary's name() function can exist at the
// same time as ours.
var userName = "Sean";
console.log(name());
function name() {
return userName;
}
}
main();
Or before!
main();
function main() {
// We are now in our own sound-proofed room and the
// character-converter libarary's name() function can exist at the
// same time as ours.
var userName = "Sean";
console.log(name());
function name() {
return userName;
}
}
A secondary concern: What are the chances that the name 'main' hasn't been used yet? ...so very, very slim.
We need MORE scoping. And some way to automatically execute our main() function.
Now we come to auto-execution functions (or self-executing, self-running, whatever).
((){})();
The syntax is awkward as sin. However, it works.
When you wrap a function definition in parentheses, and include a parameter list (another set or parentheses!) it acts as a function call.
So lets look at our code again, with some self-executing syntax:
(function main() {
var userName = "Sean";
console.log(name());
function name() {
return userName;
}
}
)();
So, in most tutorials you read, you will now be bombarded with the term 'anonymous self-executing' or something similar.
After many years of professional development, I strongly urge you to name every function you write for debugging purposes.
When something goes wrong (and it will), you will be checking the backtrace in your browser. It is always easier to narrow your code issues when the entries in the stack trace have names!
Self-invocation (also known as
auto-invocation) is when a function
executes immediately upon its
definition. This is a core pattern and
serves as the foundation for many
other patterns of JavaScript
development.
I am a great fan :) of it because:
It keeps code to a minimum
It enforces separation of behavior from presentation
It provides a closure which prevents naming conflicts
Enormously – (Why you should say its good?)
It’s about defining and executing a function all at once.
You could have that self-executing function return a value and pass the function as a param to another function.
It’s good for encapsulation.
It’s also good for block scoping.
Yeah, you can enclose all your .js files in a self-executing function and can prevent global namespace pollution. ;)
More here.
Namespacing. JavaScript's scopes are function-level.
I can't believe none of the answers mention implied globals.
The (function(){})() construct does not protect against implied globals, which to me is the bigger concern, see http://yuiblog.com/blog/2006/06/01/global-domination/
Basically the function block makes sure all the dependent "global vars" you defined are confined to your program, it does not protect you against defining implicit globals. JSHint or the like can provide recommendations on how to defend against this behavior.
The more concise var App = {} syntax provides a similar level of protection, and may be wrapped in the function block when on 'public' pages. (see Ember.js or SproutCore for real world examples of libraries that use this construct)
As far as private properties go, they are kind of overrated unless you are creating a public framework or library, but if you need to implement them, Douglas Crockford has some good ideas.
I've read all answers, something very important is missing here, I'll KISS. There are 2 main reasons, why I need Self-Executing Anonymous Functions, or better said "Immediately-Invoked Function Expression (IIFE)":
Better namespace management (Avoiding Namespace Pollution -> JS Module)
Closures (Simulating Private Class Members, as known from OOP)
The first one has been explained very well. For the second one, please study following example:
var MyClosureObject = (function (){
var MyName = 'Michael Jackson RIP';
return {
getMyName: function () { return MyName;},
setMyName: function (name) { MyName = name}
}
}());
Attention 1: We are not assigning a function to MyClosureObject, further more the result of invoking that function. Be aware of () in the last line.
Attention 2: What do you additionally have to know about functions in Javascript is that the inner functions get access to the parameters and variables of the functions, they are defined within.
Let us try some experiments:
I can get MyName using getMyName and it works:
console.log(MyClosureObject.getMyName());
// Michael Jackson RIP
The following ingenuous approach would not work:
console.log(MyClosureObject.MyName);
// undefined
But I can set an another name and get the expected result:
MyClosureObject.setMyName('George Michael RIP');
console.log(MyClosureObject.getMyName());
// George Michael RIP
Edit: In the example above MyClosureObject is designed to be used without the newprefix, therefore by convention it should not be capitalized.
Scope isolation, maybe. So that the variables inside the function declaration don't pollute the outer namespace.
Of course, on half the JS implementations out there, they will anyway.
Is there a parameter and the "Bunch of code" returns a function?
var a = function(x) { return function() { document.write(x); } }(something);
Closure. The value of something gets used by the function assigned to a. something could have some varying value (for loop) and every time a has a new function.
Here's a solid example of how a self invoking anonymous function could be useful.
for( var i = 0; i < 10; i++ ) {
setTimeout(function(){
console.log(i)
})
}
Output: 10, 10, 10, 10, 10...
for( var i = 0; i < 10; i++ ) {
(function(num){
setTimeout(function(){
console.log(num)
})
})(i)
}
Output: 0, 1, 2, 3, 4...
Short answer is : to prevent pollution of the Global (or higher) scope.
IIFE (Immediately Invoked Function Expressions) is the best practice for writing scripts as plug-ins, add-ons, user scripts or whatever scripts are expected to work with other people's scripts. This ensures that any variable you define does not give undesired effects on other scripts.
This is the other way to write IIFE expression. I personally prefer this following method:
void function() {
console.log('boo!');
// expected output: "boo!"
}();
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/void
From the example above it is very clear that IIFE can also affect efficiency and performance, because the function that is expected to be run only once will be executed once and then dumped into the void for good. This means that function or method declaration does not remain in memory.
One difference is that the variables that you declare in the function are local, so they go away when you exit the function and they don't conflict with other variables in other or same code.
First you must visit MDN IIFE , Now some points about this
this is Immediately Invoked Function Expression. So when your javascript file invoked from HTML this function called immediately.
This prevents accessing variables within the IIFE idiom as well as polluting the global scope.
Self executing function are used to manage the scope of a Variable.
The scope of a variable is the region of your program in which it is defined.
A global variable has global scope; it is defined everywhere in your JavaScript code and can be accessed from anywhere within the script, even in your functions. On the other hand, variables declared within a function are defined only within the body of the function.
They are local variables, have local scope and can only be accessed within that function. Function parameters also count as local variables and are defined only within the body of the function.
As shown below, you can access the global variables variable inside your function and also note that within the body of a function, a local variable takes precedence over a global variable with the same name.
var globalvar = "globalvar"; // this var can be accessed anywhere within the script
function scope() {
alert(globalvar);
var localvar = "localvar"; //can only be accessed within the function scope
}
scope();
So basically a self executing function allows code to be written without concern of how variables are named in other blocks of javascript code.
Since functions in Javascript are first-class object, by defining it that way, it effectively defines a "class" much like C++ or C#.
That function can define local variables, and have functions within it. The internal functions (effectively instance methods) will have access to the local variables (effectively instance variables), but they will be isolated from the rest of the script.
Self invoked function in javascript:
A self-invoking expression is invoked (started) automatically, without being called. A self-invoking expression is invoked right after its created. This is basically used for avoiding naming conflict as well as for achieving encapsulation. The variables or declared objects are not accessible outside this function. For avoiding the problems of minimization(filename.min) always use self executed function.
(function(){
var foo = {
name: 'bob'
};
console.log(foo.name); // bob
})();
console.log(foo.name); // Reference error
Actually, the above function will be treated as function expression without a name.
The main purpose of wrapping a function with close and open parenthesis is to avoid polluting the global space.
The variables and functions inside the function expression became private (i.e) they will not be available outside of the function.
Given your simple question: "In javascript, when would you want to use this:..."
I like #ken_browning and #sean_holding's answers, but here's another use-case that I don't see mentioned:
let red_tree = new Node(10);
(async function () {
for (let i = 0; i < 1000; i++) {
await red_tree.insert(i);
}
})();
console.log('----->red_tree.printInOrder():', red_tree.printInOrder());
where Node.insert is some asynchronous action.
I can't just call await without the async keyword at the declaration of my function, and i don't need a named function for later use, but need to await that insert call or i need some other richer features (who knows?).
It looks like this question has been answered all ready, but I'll post my input anyway.
I know when I like to use self-executing functions.
var myObject = {
childObject: new function(){
// bunch of code
},
objVar1: <value>,
objVar2: <value>
}
The function allows me to use some extra code to define the childObjects attributes and properties for cleaner code, such as setting commonly used variables or executing mathematic equations; Oh! or error checking. as opposed to being limited to nested object instantiation syntax of...
object: {
childObject: {
childObject: {<value>, <value>, <value>}
},
objVar1: <value>,
objVar2: <value>
}
Coding in general has a lot of obscure ways of doing a lot of the same things, making you wonder, "Why bother?" But new situations keep popping up where you can no longer rely on basic/core principals alone.
You can use this function to return values :
var Test = (function (){
const alternative = function(){ return 'Error Get Function '},
methods = {
GetName: alternative,
GetAge:alternative
}
// If the condition is not met, the default text will be returned
// replace to 55 < 44
if( 55 > 44){
// Function one
methods.GetName = function (name) {
return name;
};
// Function Two
methods.GetAge = function (age) {
return age;
};
}
return methods;
}());
// Call
console.log( Test.GetName("Yehia") );
console.log( Test.GetAge(66) );
Use of this methodology is for closures. Read this link for more about closures.
IIRC it allows you to create private properties and methods.

Javascript Properties

Please let me know if question is just dumb and not answerable?
I've just started unit testing with javascript. I have been implementing this blog code into my app. I just confused with name argument being passed to function in javascript. If we talk about Java,Php or any other language they take arguments in construct function and is understandable to use within class something like
$vehicle = new Vehicle('argument here');
Class Vehicle {
protected $name;
function __construct($name) {
$this->name = $name; // we can use the property any where in the class
}
}
//Is name Property? Object? or anything else?
//javascript
(function(name) {
"use strict";
function vehicle(modal) {
this.modal = modal || 'Civic 2015';
}
name.vehicle = vehicle; //? ? ?
})(this);//also why using (this) ?
Also an example would be greatly welcomed.
Javascript doesn't have class (really) and so OOP is handled slightly differently to some of the languages you mention. Often you'll see something like this:
function Vehicle(make, color){
this.make = make;
this.color = color;
}
Vehicle.prototype.getMake = function(){
return this.make;
}
var myCar = new Vehicle('ford', 'green');
myCar.getMake(); //'ford'
As shown in this fiddle I made: https://jsfiddle.net/eqf2apwx/
There are many ways to handle JS objects, however, and I'd suggest you google it a bit, particularly 'Crockford Classless' which is a popular way of handling objects.
The function that you are using above is called self-executing immediate functions, "this" inside such functions always points to the global object, because inside functions that were invoked as functions (that is, not as constructors with new) "this" should always point to the global object.
This pattern is useful because it provides a scope sandbox for your initialization code. Think about the following common scenario: Your code has to perform some setup tasks when the page loads, such as attaching event handlers, creating objects, and so on. All this work needs to be done only once, so there’s no reason to create a reusable named function. But the code also requires some temporary variables, which you won’t
need after the initialization phase is complete. It would be a bad idea to create all those variables as globals. That’s why you need an immediate function—to wrap all your code in its local scope and not leak any variables in the global scope
However, in ECMAScript 5 in strict mode, "this" reference doesn't necessarily point to the global object so you have to adopt a different pattern when your code is in strict mode. Therefore, developers usually pass the reference to "this" from the global scope. SO in your case "this" which is passed as an argument to immediate function is a reference to the global "window" object. Also, this pattern makes the code more interoperable in environments outside the browser because you don't need to hardcode "window" inside the immediate function.

Revealing module pattern naming convention

I'd like to avoid having to remember two names for a method, one for public and one for private access. In that sense, in which case would a script fail if you use same name for both? When would following code fail?
var TestClass = function() {
function showMessage(text) {
$("div").text(text);
}
return {
showMessage: showMessage
};
}();
I've tried it in this fiddle, and it works properly in FF, IE, Chrome, Safari. JSLint has nothing to say about it either.
I've regularly see people naming private method _showMessage or showMessageFn. Is there a good reason for this?
Answer I'm looking for is that it either fails in some situations, may create confusion, or that it's just JavaScript people inventing conventions to seem smart.
This works fine - you're defining a function called showMessage() in the context of your inner function, then assigning it to the showMessage property of your exported object literal.
A property name can be any valid identifier, so showMessage is of course perfectly valid. In your example, function showMessage(text) creates an identifier called showMessage in the inner scope, referencing a function definition. You then create a separate identifier called showMessage as a property name on the object literal, which is assigned the value of the function referenced by the the inner identifier. The fact that both identifiers have the same name is irrelevant as they do not exist in the same scope.
Only problem I can see is that you should wrap the function invocation in parens, otherwise it is not immediately clear to the reader that the function is self-invoking.
So this:
var TestClass = function() {
...
}();
Becomes this:
var TestClass = (function() {
...
}());
The reason private methods are often prefixed with an underscore is simply a widely used convention - it shows that the method is intended to be private (Javascript doesn't support access modifiers, so any property or method that isn't encapsulated in a closure can be accessed from an outer scope). The accepted answer to this StackOverflow quesion sums it up perfectly.
What you are doing here is returning an object that contains the object of the function you defined.
I think that basically it's a way to show whether you are accessing the function in the same scope that it was created or in a different scope.

Javascript Mutable Parameter?

This is just a technical question about javascript. In javascript, one member of my group found something odd with javascript object creation. For some reason, the parameters in the object are already treated as members without assigning them to any member variables created in the constructor of the object. The parameters are mutable also as seen in the code block below.
Here's the code to show the testing we have being doing.
function NamedItem(name)
{
name = 5;
this.getName = function ()
{
return name;
}
}
document.write(namedItem.getName() + "\n"); //5
Is this legitimate? Is it dangerous?
That's called a closure.
Nested functions can access variables from their parent function and extend the variables' lifetimes beyond the execution of the parent function.
It has nothing to do with objects.
Just to be clear there are some potentially silly things about what you're doing. Let me explain a few principles.
If you declare a variable or variables as arguments to a function such as function(arg1, arg2), in terms of the variables themselves (and not their values) it is essentially the same as saying at the top of your function var arg1; var arg2;. The are declared for you automatically. Even if you try and redeclare them, they'll still work with the passed in arguments!
Functions are objects. Objects can have properties. Therefore functions can have properties, such as this.getName = function().
Like the #SLaks pointed out you're creating a closure in your version of the getName method. A closure captures the state of things above it when it's created. Therefore if there is a name variable in its scope when it's created, it will have access to that name variable in it's scope. It's a very normal practice in JavaScript and you've managed to create a private property (name) with a public accessor function (getName). Well done.
I assume you're using creating instances of NamedItem with the new keyword like this. var item = new NamedItem("javascripter"). Another way (and one that uses less memory than what you are doing is to add the getName() function to the prototype for NamedItem like I show below. The drawback to the prototype approach is that you could just as easily access _name directly. There are no private properties in the traditional sense in JavaScript, but some people use the underscore prefix to indicate to people that they're private and not to use them. This approach (prototypes) use less memory than your approach because if you create multiple instances of NamedItem they all share a single prototype.
Using the prototypes instead:
function NamedItem(name) {
this._name = name
}
NamedItem.prototype.getName = function() {
return this._name
}
Hope that gives you some things to think about!
J

What do you call a set of Javascript closures that share a common context?

I've been trying to learn closures (in Javascript), which kind of hurts my brain after way too many years with C# and C++. I think I now have a basic understanding, but one thing bothers me: I've visited lots of websites in this Quest for Knowledge, and nowhere have I seen a word (or even a simple two-word phrase) that means "a set of Javascript closures that share a common execution context". For example:
function CreateThingy (name, initialValue)
{
var myName = name;
var myValue = initialValue;
var retObj = new Object;
retObj.getName = function() { return myName; }
retObj.getValue = function() { return myValue; }
retObj.setValue = function(newValue) { myValue = newValue; }
return retObj;
};
From what I've read, this seems to be one common way of implementing data hiding. The value returned by CreateThingy is, of course, an object, but what would you call the set of functions which are properties of that object? Each one is a closure, but I'd like a name I can used to describe (and think about) all of them together as one conceptual entity, and I'd rather use a commonly accepted name than make one up.
Thanks!
-- Ed
Crockford popularized the term "privileged method" to name the functions that have access to the scope of its constructor (where the private members are declared).
I would call them "A set of JavaScript functions that share a common enclosing scope".
The "execution context" part of the phrase you post, can create confusion between the Execution Contexts described in the specification, the this value, which also is popularly known as "the function context" or "object context", and the function scope, which is really what is being referenced here.
You could call it a class, but it's just a hash table with a bunch of entries, some of which are functions (or closures). The more idiomatic way to do this in Javascript is through the use of prototypes.
Some links to help you:
http://javascript.crockford.com/prototypal.html
http://www.crockford.com/javascript/private.html
Its close to the module pattern. Use an expression like so:
var thingy = (function(specObj) {
var my = {},
privateVar = blah,
someOtherPrivateVar = [];
my.getSomeVal() {
return specObj.someVal;
}
my.getAnotherVal() {
return specObj.AnotherVal;
}
}({
someVal: "value",
anotherVal: "foo"
}));
I initialized with an object literal because using a named object would allow the state of thingy to be changed by changing the named object. There are other options to do this.
Here's another good link on variations of the module pattern:
http://www.adequatelygood.com/2010/3/JavaScript-Module-Pattern-In-Depth
Almost goes without saying, but Crockford's Javascript: The Good Parts contains a good treatment of this style and its specific benefits.

Categories

Resources