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
Related
This question already has answers here:
Why use named function expressions?
(5 answers)
Closed 4 years ago.
Here is the code sample I have a question about:
var javascriptObject = {
functionName1: function functionName2() {
}
}
I understand the concept of an object in the javascript. I understand everything in the code sample except the functionName2 what is its purpose?
And I saw the code in the real life projects:
init: function init() {
init._base.call(this);
}
The code above does not work if I get rid from the second init. What does that second function name mean in javascript?
Object in JS are just name value pairs nothing more
var javascriptObject = {
functionName1: function functionName2() {
}
}
So what your doing is having a object which has a name of functionName1 which has the value of
function functionName2() {}
The name of the function stored in this value is functionName2 but this also could be omitted since it is not necessary to invoke the function.
For example you could run the function without the functionName2
var javascriptObject = {
functionName1: function () {
return 5;
}
};
var bar = javascriptObject.functionName1();
console.log(bar);
This question already has answers here:
How does the "this" keyword work, and when should it be used?
(22 answers)
How to access the correct `this` inside a callback
(13 answers)
Closed 5 years ago.
class Foo {
constructor() {
this.foobar = "foobar";
}
bar() {
let _this = this;
return function() {
try {
alert("Attempt 1: "+foobar);//ReferenceError: foobar is not defined
myMethod();
} catch(err) {console.log(err);}
try {
alert("Attempt 2: "+this.foobar);//TypeError: this is undefined
this.myMethod();
} catch(err) {console.log(err);}
try{
alert("Attempt 3: "+_this.foobar);//Works!
_this.myMethod();
} catch(err) {console.log(err);}
}();
}
myMethod() {
alert("myMethod()");
}
}
new Foo().bar();
The above example is very simplified - the anonymous function inside bar() was a jQuery call originally, but for the sake of the question I didn't include that.
Why don't attempts 1 and 2 work? Do I have to use the _this trick to reference class variables/methods? How do I reference class variables/methods from nested functions?
Are you familiar with how the this keyword works in JavaScript? It's value will depend on how the function is called, not in how it is defined. For example, if you do the following:
var dog = {
greeting:"woof",
talk:function (){
console.log(this.greeting);
}
};
var cat={
greeting:"meow",
talk:dog.talk
};
dog.talk();
cat.talk();
You will see that when the talk function is called as a method of an object, that object will be used as the value of this.
The same happens with ES6 classes, where class methods are still JavaScript functions and the rules for deciding the value of this still apply. If you want to avoid declaring an auxiliar variable, you should look into using bind:
var mammal = {
greeting:"<noise>",
getTalk:function (){
return function(){
console.log(this.greeting);
};
},
getTalkBinded:function (){
return (function(){
console.log(this.greeting)
}).bind(this);
}
};
var dog={
greeting:"woof",
talk:mammal.getTalk(),
talkBinded:mammal.getTalkBinded()
};
var cat={
greeting:"meow",
talk:mammal.getTalk(),
talkBinded:mammal.getTalkBinded()
};
dog.talk();
cat.talk();
dog.talkBinded();
cat.talkBinded();
You are returning self-execution function execution result and during that function execution this it global context(not your class object). to make it work use () => {}() arrow function call syntax, as it captures current context, or function() { }.bind(this)().
See this simple example,
function a(){
this.someProp = 5;
console.log(this);
var _this = this; //so we explicitly store the value of `this` to use in a nested function
return function(){
//value of `this` will change inside this function
this.anotherProp = 6;
console.log(this);
//to use the methods and props of original function use `_this`
console.log(_this)
}
}
var c = a.call({}) //prints {someProp: 5}
c.call({}) //prints {anotherProps: 6} {someProp: 5}
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.
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
}
This question already has answers here:
Location of parenthesis for auto-executing anonymous JavaScript functions?
(4 answers)
Closed 8 years ago.
Both of these code blocks below alert foo then bar. The only difference is })() and }()).
Code 1:
(function()
{
bar = 'bar';
alert('foo');
})();
alert(bar);
Code 2:
(function()
{
bar = 'bar';
alert('foo');
}());
alert(bar);
So is there any difference, apart from the syntax?
No; they are identical
However, if you add new beforehand and .something afterwards, they will be different.
Code 1
new (function() {
this.prop = 4;
}) ().prop;
This code creates a new instance of this function's class, then gets the prop property of the new instance.
It returns 4.
It's equivalent to
function MyClass() {
this.prop = 4;
}
new MyClass().prop;
Code 2
new ( function() {
return { Class: function() { } };
}() ).Class;
This code calls new on the Class property.
Since the parentheses for the function call are inside the outer set of parentheses, they aren't picked up by the new expression, and instead call the function normally, returning its return value.
The new expression parses up to the .Class and instantiates that. (the parentheses after new are optional)
It's equivalent to
var namespace = { Class: function() { } };
function getNamespace() { return namespace; }
new ( getNamespace() ).Class;
//Or,
new namespace.Class;
Without the parentheses around the call to getNamespace(), this would be parsed as (new getNamespace()).Class — it would call instantiate the getNamespace class and return the Class property of the new instance.
There's no difference - the opening brace only serves as a syntactic hint to tell the parser that what follows is a function expression instead of a function declaration.
There's no difference. Both are function expressions.
There is be a third way, too:
+function() {
bar = 'bar';
alert('foo');
}();
(instead of the + another operator would work, too)
The most common way is
(function() {
// ...
})();
though.