Today while working my mind was stack at some point in javascript.
I want to know that what is basic difference between
function FunctionName(){
//Code goes here;
}
And
var MyFuncCollection = new Object();
MyFuncCollection.FunctionName = function(){
//Code goes here;
}
Both are working same. Then what is difference between then. Is there any advantage to use function with object name?
I have read Question. But it uses variable and assign function specific variable. I want to create object and assign multiple function in single object.
The first one defines a global function name. If you load two libraries, and they both try to define FunctionName, they'll conflict with each other. You'll only get the one that was defined last.
The second one just has a single global variable, MyFuncCollection. All the functions are defined as properties within that variable. So if you have two collections that try to define the same function name, one will be FuncCollection1.FunctionName, the other will be FuncCollection2.FunctionName, and there won't be any conflict.
The only conflict would be if two collections both tried to use the same name for the collection itself, which is less likely. But this isn't totally unheard of: there are a few libraries that try to use $ as their main identifier. jQuery is the most prominent, and it provides jQuery.noConflict() to remove its $ binding and revert to the previous binding.
The short answer is, the method in object context uses the Parent Objects Context, while the "global" function has its own object context.
The long answer involves the general object-oriented approach of JavaScript, though everything in JavaScript is an object you may also create arrays with this Method.
I can't really tell you why, but in my experience the best function definition is neither of the top mentioned, but:
var myFunction = function(){};
It is possible to assign function to variables, and you may even write a definition like this:
MyObject.myMethod = function(){};
For further reading there are various online Textbooks which can give you more and deeper Information about this topic.
One main advantage I always find is cleaner code with less chance of overwriting functions. However it is much more than that.
Your scope changes completely inside the object. Consider the following code ::
Function:
function FunctionName(){
return this;
}
FunctionName()
Returns:
Window {top: Window, location: Location, document: document, window: Window, external: Object…}
Object:
var MyFuncCollection = new Object();
MyFuncCollection.FunctionName = function(){
return this;
}
MyFuncCollection.FunctionName()
Returns:
Object {}
This leads to some nice ability to daisy chain functions, amongst other things.
The first:
function functionName (){
//Code goes here;
}
Is a function declaration. It defines a function object in the context it's written in.
Notice: this doesn't have to be the global context and it doesn't say anything about the value of this inside it when it's invoked. More about scopes in JavaScript.
Second note: in most style guides functions are declared with a capitalized name only if it's a constructor.
The second:
var myFuncCollection = {};
myFuncCollection.functionName = function () {
//Code goes here;
};
notice: don't use the new Object() syntax, it's considered bad practice to use new with anything other then function constructors. Use the literal form instead (as above).
Is a simple assignment of a function expression to a property of an Object.
Again the same notice should be stated: this says nothing about the value of this when it's invoked.
this in JavaScript is given a value when the function object is invoked, see here for details.
Of course, placing a function on an Object help avoiding naming collisions with other variables/function declarations in the same context, but this could be a local context of a function, and not necessarily the global context.
Other then these differences, from the language point of view, there's no difference whatsoever about using a bunch of function declarations or an Object with bunch of methods on it.
From a design point of view, putting methods on an Object allows you to group and/or encapsulate logic to a specific object that should contain it. This is the part of the meaning of the Object Oriented Programming paradigm.
It's also good to do that when you wish to export or simply pass all these functions to another separate module.
And that's about it (:
Related
I'm studying THREE.js and noticed a pattern where functions are defined like so:
var foo = ( function () {
var bar = new Bar();
return function ( ) {
//actual logic using bar from above.
//return result;
};
}());
(Example see raycast method here).
The normal variation of such a method would look like this:
var foo = function () {
var bar = new Bar();
//actual logic.
//return result;
};
Comparing the first version to the normal variation, the first seems to differ in that:
It assigns the result of a self-executing function.
It defines a local variable within this function.
It returns the actual function containing logic that makes use of the local variable.
So the main difference is that in the first variation the bar is only assigned once, at initialization, while the second variation creates this temporary variable every time it is called.
My best guess on why this is used is that it limits the number of instances for bar (there will only be one) and thus saves memory management overhead.
My questions:
Is this assumption correct?
Is there a name for this pattern?
Why is this used?
Your assumptions are almost correct. Let's review those first.
It assigns the return of a self-executing function
This is called an Immediately-invoked function expression or IIFE
It defines a local variable within this function
This is the way of having private object fields in JavaScript as it does not provide the private keyword or functionality otherwise.
It returns the actual function containing logic that makes use of the local variable.
Again, the main point is that this local variable is private.
Is there a name for this pattern?
AFAIK you can call this pattern Module Pattern. Quoting:
The Module pattern encapsulates "privacy", state and organization using closures. It provides a way of wrapping a mix of public and private methods and variables, protecting pieces from leaking into the global scope and accidentally colliding with another developer's interface. With this pattern, only a public API is returned, keeping everything else within the closure private.
Comparing those two examples, my best guesses about why the first one is used are:
It is implementing the Singleton design pattern.
One can control the way an object of a specific type can be created using the first example. One close match with this point can be static factory methods as described in Effective Java.
It's efficient if you need the same object state every time.
But if you just need the vanilla object every time, then this pattern will probably not add any value.
It limits the object initialization costs and additionally ensures that all function invocations use the same object. This allows, for example, state to be stored in the object for future invocations to use.
While it's possible that it does limit memory usage, usually the GC will collect unused objects anyways, so this pattern is not likely to help much.
This pattern is a specific form of closure.
I'm not sure if this pattern has a more correct name, but this looks like a module to me, and the reason it is used is to both encapsulate and to maintain state.
The closure (identified by a function within a function) ensures that the inner function has access to the variables within the outer function.
In the example you gave, the inner function is returned (and assigned to foo) by executing the outer function which means tmpObject continues to live within the closure and multiple calls to the inner function foo() will operate on the same instance of tmpObject.
The key difference between your code and the Three.js code is that in the Three.js code the variable tmpObject is only initialised once, and then shared by every invocation of the returned function.
This would be useful for keeping some state between calls, similar to how static variables are used in C-like languages.
tmpObject is a private variable only visible to the inner function.
It changes the memory usage, but its not designed to save memory.
I'd like to contribute to this interesting thread by extending to the concept of the revealing module pattern, which ensures that all methods and variables are kept private until they are explicitly exposed.
In the latter case, the addition method would be called as Calculator.add();
In the example provided, the first snippet will use the same instance of tmpObject for every call to the function foo(), where as in the second snippet, tmpObject will be a new instance every time.
One reason the first snippet may have been used, is that the variable tmpObject can be shared between calls to foo(), without its value being leaked into the scope that foo() is declared in.
The non immediately executed function version of the first snippet would actually look like this:
var tmpObject = new Bar();
function foo(){
// Use tmpObject.
}
Note however that this version has tmpObject in the same scope as foo(), so it could be manipulated later.
A better way to achieve the same functionality would be to use a separate module:
Module 'foo.js':
var tmpObject = new Bar();
module.exports = function foo(){
// Use tmpObject.
};
Module 2:
var foo = require('./foo');
A comparison between the performance of an IEF and a named foo creator function: http://jsperf.com/ief-vs-named-function
Out of the following 2 ways of calling a method in JavaScript;
myFunc(params);
obj.myFunc();
My questions are;
For each of them, what exactly is the difference in accessing the values (for params/obj) inside myFunc()
For the 1st case, when we use "this" inside myFunc(), it would refer to global obj (window). What about the second case?
What are the use cases for using either of the 2 techniques?
You can add any other significant differences between the two techniques as well.
Since you did not provide enough context, I will assume your two function calls:
1. myFunc(params)
2. obj.myFunc()
correspond to the following definitions of myFunc() and obj.myFunc():
function myFunc(params) { }
var obj = {
myFunc: function() { }
};
The first call myFunc(params) is a call to the global function myFunc() with params passed as the parameter. this will refer to the global object, which is window inside browsers (You can test this by doing window.myFunc === myFunc, which will return true)
The second call obj.myFunc() is call to the method myFunc() inside the obj object. this will refer to obj, not window.
Regarding use cases, that will depend on your design, but global functions are obviously not recommended as they pollute the global namespace (i.e. you may redefine the global myFunc() by accident without noticing it).
The second approach is common when you need a pseudo javascript namespace
I will re-render your questions:
3- Cases: your_obj.function(): this one is usually used in the single page web app or you have many module one one page and you want to separate modules for maintaining purposes. While myfunction(args) is a global usage.
2 - you can invoke it by: window.your_obj.function()
1 - I'm not sure what you mean :)
Those are my opinion.
I know I can define properties on functions, which can then be accessed from within the function. Right now, the only syntax I can work out involves two statements. Is there a more concise way to express the following:
function myFunc() {
// do some work
}
myFunc.myProp = 0;
I'm not looking for a solution that is fewer characters -- this isn't code golf. I'm asking something more along the lines of "are there different patterns of function declaration that have this other desirable merit?" This is almost about ways to use closures (because I suspect the answer lies there).
Thanks!
Especially if you want to access properties of the function from inside the function itself, you're better off doing this:
var theFunction = function() {
function theRealFunction() {
// the code
if (theRealFunction.something == "not whatever")
// do something
// more code
}
theRealFunction.something = "whatever";
return theRealFunction;
}();
What that does is wrap your function declaration up in an anonymous function. The problem with accessing function properties via the function name is that it must do that by finding the function's name in the surrounding scope. That's kind-of icky, but at least this way it involves a scope that's essentially private. It'll work whether or not the resulting function (returned as the return value of the anonymous function) is assigned to a different variable, passed to a function as a handler function, etc.
This really, really all depends. If you're looking for private variables, then you can easily return a function from the function -- an inner-function will contain access to its parent's scope.
var outer_function = (function () {
var private_var = "secret",
public_var = "public",
inner_function = function () {
return private_var;
};
inner_function.public_var = public_var;
return inner_function;
}());
outer_function now equals inner_function, with the benefit of having access to the enclosed data. Any properties attached to the inner (in the way you did) will now be accessible as public properties of outer.
To this end, you can return, say, a constructor for a class, with public-static properties, with the enclosed vars acting as private-static properties, shared between every instance of the "class" you build.
Not exactly the answer to your question, but if you ever want to read up some different design patterns that can be used when defining a javascript function, this is one of the best articles I've ever read on the topic:
http://www.klauskomenda.com/code/javascript-programming-patterns/
I'm trying to get a really solid grasp of JavaScript and I'm stumbling across a big issue for me. I'm used to working in C languages and one of the barriers I'm finding is dealing with the prototype functionality of JavaScript and when functions are declared, as it is concerned with the order of execution.
For instance, take the following code:
var construct = new Constructor(); //I can do this even if its above the declaration of the object.
construct.MyPrivilagedFunction(); //Can do this here too, even though it's above the function declaration.
construct.MyPublicFunction(); //Can't do this because it is above the function declaration.
function Constructor() {
//Private member
var m_Ding = "Ding!";
//Accessible publicly and has access to private member.
this.MyPrivilagedFunction = function() {
console.log(m_Ding);
}
}
Constuctor.prototype.MyPublicFunction = function() {
//Doesn't have access to private members. This doesn't work.
console.log(m_Ding);
}
I understand that prototyping provides better performance because then a copy of the function is not stored on every instance of your object and instead every instance is referring to the same function (and I guess each new instance could be considered a whole new object type?). However, prototyping does not allow me to use a function before it is defined. Furthermore, a prototyped function doesn't have access to a private member of the object.
This is only really a problem because I am working on a project where two objects will need to use each other's functions. If I place one object earlier in the code, it won't have access to the second object because prototyped functions adhere to the order of execution (top to bottom).
Side Note: I'm also aware that my object should probably be an object literal ( like object={property:value}), but I'm still trying to get a solid grasp on scope and prototyping to attempt to deal with that for now.
if i get you well, the root of your problem is "two objects will need to use
each other's functions."
But in fact Javascript is not a typed language : define TypeA, define TypeB,
after that you can use instances : typeA and typeB objects with no issue.
var Speaker = function(name) {
this.name = name ;
};
Speaker.prototype.sayHi = function(aMate) {
amate.listenTo(this, ' Hi ' + this.mate.name ); // no type checking performed here
// so no issue even if Listener
// is not defined yet
};
var Listener = function(name) {
this.name = name;
this.knownMate = [];
};
Listener.prototype.listenTo = function (mate, words) {
this.knownMate.push(mate);
};
var aSpeaker = new Speaker('Joe');
var aListener = new Listener('Bobby');
aSpeaker.sayHi(aListener);
And by the way, you do not have private members in Javascript, only closures.
So yes, any function defined outside the scope of the 'private' member will
not be able to read/write to it.
Be advised also that, if performance is an issue, closures are slower on the
less performant js engine.
A not-so-bad solution to have 'pseudo-private' members is to define those members
as not enumerable with Object.defineProperty()
(watch here :
https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Object/defineProperty )
The order of execution is the one you write. There are only two exceptions from the rule "everything below is irrelevant": variable and function declarations are hoisted, i.e. you can use (assign to, call) them above. And beware of the difference between function declarations and function expressions.
var construct = new Constructor() //I can do this even if its above the declaration of the object.
Declaration of the constructor function you want to say.
construct.MyPrivilagedFunction(); //Can do this here too, even though it's above the function declaration.
There is no function declaration in here. The privileged method was created (with an assignment of a function expression to a property) during the execution of the constructor function (see above).
construct.MyPublicFunction(); //Can't do this because it is above the function declaration.
Again, it is no function declaration but an assignment of a function expression. And it didn't happen yet, because it is below.
This is only really a problem because I am working on a project where two objects will need to use each other's functions. If I place one object earlier in the code, it won't have access to the second object because prototyped functions adhere to the order of execution (top to bottom).
You usually don't need access to anything before you call anything. "Declare" everything at first (constructor, prototype properties), then instantiate.
I have some third-party Javascript that has statements like this:
FOO = function() {
...functions() ...
return { hash }
}();
It is working as designed but I'm confused by it. Can anybody define what this structure is doing? Is it just a weird way to create a class?
This is a technique that uses closure. The idiom is well-known, but confusing when you first see it. FOO is defined as the object that the outermost function() returns. Notice the parenthesis at the end, which causes the function to evaluate and return { hash }.
The code is equivalent to
function bar() {
...functions() ...
return { hash }
};
FOO = bar();
So FOO is equal to { hash }. The advantage of this is that hash, whatever it is, has access to stuff defined inside the function(). Nobody else has access, so that stuff is essentially private.
Google 'Javascript closure' to learn more.
Js doesn't really have classes, per se, but "prototypes". This means that no two objects are ever of the same "type" in the normal type-safe sense, and you can dynamically add members to one instance while leaving the other unmolested. (which is what they have done).
Believe it or not, the syntax they have used is probably the most lucid, as it doesn't try to hide behind some C-style class syntax.
Doug Crockford's Javascript: The Good Parts is a quick read, and the best introduction to OOP in js that I've come across.
That's not actually a class, just an object. I'd recommend reading this: http://javascript.crockford.com/survey.html
Because JavaScript doesn't have block scope, your choice is (mostly) to have all variable reside in global or function scope. The author of your snippet wants to declare some local variables that he doesn't want to be in the global scope, so he declares an anonymous function and executes it immediately, returning the object he was trying to create. That way all the vars will be in the function's scope.
The parans at the end make this the Module Pattern, which is basically a way to have a single instance of an object(Singleton) while also using private variables and functions.
Since there's closures hash, if it's itself an object or function, will have access to all variables declared within that anonymous Singleton object.
You're missing an open parens, but it is basically a way of usually hiding information within an object i.e. a way of setting up private and privelaged methods.
For example
var foo = (function() {
/* function declarations */
return { /* expose only those functions you
want to expose in a returned object
*/
}
})();
Take a look at Papa Crockford's Private Members in JavaScript. This is basically the pattern you are seeing, but in a slightly different guise. The function declarations are wrapped in a self-invoking anonymous function - an anonymous function that is executed as soon as it's declared. Since the functions inside of it are scoped to the anonymous function, they will be unreachable after the anonymous function has executed unless they are exposed through a closure created by referencing them in the object returned from the execution of the anonymous function.
It's generally referred to as the Module Pattern.