what are the various ways to define function in javascript [duplicate] - javascript

This question already has answers here:
var functionName = function() {} vs function functionName() {}
(41 answers)
Closed 6 years ago.
Which is is the best way to define a function in javascript . how to define a function using ':' like function_Name : function(){} .

Hope this will be useful
Named function
function someName(){
//rest of code
}
can be called by someName();
Function expression
var someName = function(){}
can be called by someName()
IIFE
(function(someParam){
//rest of code
}(params))
IIFE can also can also written in this way
+function(someParam){
//rest of code
}(someParam)
Named function expression
var someVar = function someFoo(){};
this is called by someVar() . someFoo is only accessible inside itself
Arrow function(aka fat arrow)
var someVar= (param1, param2) => {return somereturn}
Function constructor
var adder = new Function('a', 'b', 'return a + b');
Beside this you can also take a look at call & apply

There is no "best" way to define a function, it depends on your needs. For example if you have a function that validates something it makes sense to put it into a variable like Pugazh said:
var foo = function(){
if (/*some condition*/) {
//do something...;
return true;
}
else {
return false;
}
And then use it like alert(foo()); and it will execute the function and return the value (true or false).
Sometimes you want a named function you can call with options like:
function SaveData(data) {
//Code to save something
}
And then call it like SaveData("Hello World");
And sometimes you just add a function without a name that is executed as a callback (e.g. in jquery) or when you perform a specific action but you define it at the event and not as a named function.
All types of functions have their use cases.

Related

difference between (callback) and (() => callback()) in typescript (angular2) [duplicate]

This question already has answers here:
How to access the correct `this` inside a callback
(13 answers)
Closed 1 year ago.
Normally I'd assign an alternative "self" reference when referring to "this" within setInterval. Is it possible to accomplish something similar within the context of a prototype method? The following code errors.
function Foo() {}
Foo.prototype = {
bar: function () {
this.baz();
},
baz: function () {
this.draw();
requestAnimFrame(this.baz);
}
};
Unlike in a language like Python, a Javascript method forgets it is a method after you extract it and pass it somewhere else. You can either
Wrap the method call inside an anonymous function
This way, accessing the baz property and calling it happen at the same time, which is necessary for the this to be set correctly inside the method call.
You will need to save the this from the outer function in a helper variable, since the inner function will refer to a different this object.
var that = this;
setInterval(function(){
return that.baz();
}, 1000);
Wrap the method call inside a fat arrow function
In Javascript implementations that implement the arrow functions feature, it is possible to write the above solution in a more concise manner by using the fat arrow syntax:
setInterval( () => this.baz(), 1000 );
Fat arrow anonymous functions preserve the this from the surrounding function so there is no need to use the var that = this trick. To see if you can use this feature, consult a compatibility table like this one.
Use a binding function
A final alternative is to use a function such as Function.prototype.bind or an equivalent from your favorite Javascript library.
setInterval( this.baz.bind(this), 1000 );
//dojo toolkit example:
setInterval( dojo.hitch(this, 'baz'), 100);
i made a proxy class :)
function callback_proxy(obj, obj_method_name)
{
instance_id = callback_proxy.instance_id++;
callback_proxy.instances[instance_id] = obj;
return eval('fn = function() { callback_proxy.instances['+instance_id+'].'+obj_method_name+'(); }');
}
callback_proxy.instance_id = 0;
callback_proxy.instances = new Array();
function Timer(left_time)
{
this.left_time = left_time; //second
this.timer_id;
this.update = function()
{
this.left_time -= 1;
if( this.left_time<=0 )
{
alert('fin!');
clearInterval(this.timer_id);
return;
}
}
this.timer_id = setInterval(callback_proxy(this, 'update'), 1000);
}
new Timer(10);

Why are functions assigned to variables in the module pattern? [duplicate]

This question already has answers here:
var functionName = function() {} vs function functionName() {}
(41 answers)
Closed 9 years ago.
In the Module Pattern example from Addy Osmani, a private function is assigned to a variables as shown in this example:
var myNamespace = (function () {
var myPrivateVar, myPrivateMethod;
// A private counter variable
myPrivateVar = 0;
// A private function which logs any arguments
myPrivateMethod = function( foo ) {
console.log( foo );
};
return {
// A public function utilizing privates
myPublicFunction: function( bar ) {
// Increment our private counter
myPrivateVar++;
// Call our private method using bar
myPrivateMethod( bar );
}
};
})();
I would have simply written the private function as:
function myPrivateMethod( foo ) {
console.log( foo );
};
Is there any reason to assign the function to a variable if it's not used as a delegate? I'm looking at some code that uses this pattern consistently and I'm finding it hard to follow. For example:
var _initializeContext = function() { // many lines of code }
This is a function declaration vs a function expression issue. To some degree it's a stylistic choice. What you do need to be aware of is that function declarations get hoisted by the JS interpreter, which function expressions aren't. Some people prefer to use function expressions because they don't like the idea of their code being rearranged.
You might want to check out:
var functionName = function() {} vs function functionName() {}
http://javascriptweblog.wordpress.com/2010/07/06/function-declarations-vs-function-expressions/
http://www.adequatelygood.com/JavaScript-Scoping-and-Hoisting.html

Does it matter which way named functions are declared? [duplicate]

This question already has answers here:
var functionName = function() {} vs function functionName() {}
(41 answers)
Closed 9 years ago.
I see named functions exampled this way:
var clearClick = function() {
// do something
}
...and then used for binding like so:
$("#clear").bind(click, clearClick);
...or with the "shorthand" methodology thus:
$("#clear").click(clearClick);
But why not use a more "normal" (similar to other programming languages) construct like this:
function clearClick() {
// do something
}
It works the same, doesn't it? Is there any disadvantage to defining functions in this traditional way? Is the previous way just jQuerians flaunting their newfangledness?
This works Function expression
var clearClick = function() {
// do something
}
$("#clear").bind(click, clearClick);
This does not work Function expression. The order matters here.
$("#clear").bind(click, clearClick);
var clearClick = function() {
// do something
}
But when you declare your function using a function declaration the order does not matter.
One more advantage of the below syntax is that the function name appears in debugger.
function clearClick() {
// do something
}
One reason you might want to do it is how this works:
var clearClick;
$("#clear").click(clearClick);
clearClick = function() {
// do something
}
... lots of stuff in here ...
clearClick = function() {
// do something different
}

How to call a function whose name is defined in a string? [duplicate]

This question already has answers here:
How to execute a JavaScript function when I have its name as a string
(36 answers)
Closed 9 years ago.
I am passing function A's or B's name in a parameter based on the situation to another function C. How can I call it in function C?
if A is defined globally, then window["A"](). However, there's no need to do that in javascript. Just pass the function itself rather than its name:
function foo() {...}
// BAD
function callFunc(someName) { window[someName]() }
callFunc("foo")
// GOOD
function callFunc(someFunc) { someFunc() }
callFunc(foo)
Like this:
window[varName]()
assuming it is in global scope
If you have
function A() {}
function B() {}
then you can do
function C(parm) {
parm();
}
if you call it with C(A) or C(B)
DEMO
You could assign the functions to properties of an object. Then in your executing function reference the property by name given the parameter passed to the function.
var myFuncs = {
a: function(){
alert("Hello");
},
b: function(){
alert("Goodbye");
}
};
function execute(name){
myFuncs[name]();
}
execute("a");
execute("b");
Working Example http://jsfiddle.net/ud6BS/

How to execute a YUI function from Javascript?

How can i call a YUI function that is wrapped inside a YUI().use from javascript?
example
Below is a YUI function "runShowAnim" which executes animShow.run(); for an animation effect...
var runShowAnim = function(e) {
animShow.run();
};
I want this effect to happen when i validate something in a javascript function. I tried to call it as below. But it doesn't seem to work.
function notifyUser(message) {
document.getElementById("msgArea").innerHTML = message;
runShowAnim();
}
I achieved this by sandwiching the YUI function completely inside a function and calling that function..
var runShowAnim = function() {
YUI().use('anim', 'node', function(Y) {
var animShow = new Y.Anim({
node: '#msgArea',
to: { height: 50,opacity:1 }
});
animShow.run();
});
};
now i can call runShowAnim without any problem like in the below sample function..
function notifyUser(message) {
document.getElementById("msgArea").innerHTML = message;
runShowAnim();
}
If you want to call a function, you have to suffix the function name with () and include 0 or more comma separated arguments between them.
runShowAnim();
If the function doesn't have global scope (as yours will have if it is declared inside a function passed to use()) and not passed outside in some way then you can only do this from the same scope.
I think you're missing the parentheses.
function notifyUser(message) {
document.getElementById("msgArea").innerHTML = message;
runShowAnim(); // right here
}
YUI.thefunction()?
I think you need to call it with namespace too
something similar to
var X = function(){};
X.Y = function(){};
X.Y.Z = function(){};
X.Y.Z.foo = function(e){alert(e);}
//foo("me");<-error
X.Y.Z.foo("me");
If you want to call a function that has been defined inside the closure (the function passed as the last parameter to YUI.use) from outside it, you need to expose the function globally.
Either define a global variable outside the closure and assign your function to it, or assign your function to the window object
i.e.
var runShowAnim;
YUI().use(function(e){
runShowAnim = function(){alert('called');}
});
runShowAnim();

Categories