JavaScript function different syntax? [duplicate] - javascript

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
What is the difference between a function expression vs declaration in JavaScript?
This JavaScript syntax I haven't seen till now, what does it do really?
What is the difference between the following two ways of writing a function? I've seen both used, but I'm not sure which one is 'correct'.
function init() {
}
init: function() {
},
And what are the advantages to writing it the second way?

Function declaration
function init() {
}
Function expression
var init = function() {
};
The primary differences have to do with Variable Hoisting in JavaScript. You can read more here: http://www.adequatelygood.com/2010/2/JavaScript-Scoping-and-Hoisting and http://javascriptweblog.wordpress.com/2010/07/06/function-declarations-vs-function-expressions/
By your example, I believe you are also interested in defining anonymous functions in object literals. Here is an example:
//obj is the object name
var obj = {
//init is the property name or key and the anonymous function is the value
init: function() {
},
anotherProp: 'some value'
};
This would be used like so:
obj.init();
alert(obj.anotherPorp);
In object literals different properties of the object are defined with a key: value syntax and use commas to separate them.
I would recommend going through this free series on JavaScript http://learn.appendto.com/lessons, it will answer a lot of these questions for you and give you a solid base to becoming a JS developer.

The second one can only be used in the context of an object literal:
var myNamespace = {
func1: function () {
// do something
},
func2: function () {
// do something else
},
someValue = 5
};
The first form is executed as a statement. It is equivalent to:
var init = function () {
// do something
};

The first example defines a function in the global scope which can be called with init(). The second defines a property of an object called init that is the function declaration to the right.
Generally, the second example provides a smaller scope in which you could execute the function.
First example allows you to call the function like so:
init();
And the second, more likely this:
var thing = function() {
init: function() { }
};
thing.init();

Try to always use:
init: function (){
}
when writing an object literal.
When you're trying to process a global function set it as a var instead, so:
var init = function(){
}
Remember, each has its place, but I've personally become fond of writing a namespace for the project I'm working on and using an object literal.
Now both of these will only be available in the object as soon as the object is set. The other method is a little sloppier and less used now, but can be called no matter the order of operations, so it can be called before or after it's set in the code... Again, this is being abandoned in a lot of cases.
function init(){
}

Related

What's the difference between these two function expressions?

Please correct me if I am wrong. The snippet below is a function statement:
function foo() {}
where as the ones below are all function expressions.
var foo = function() { } // or
var foo = function foo() { } // or
var foo = new function() { }
My question is, what is the difference between these two forms of a function expression?
var foo = function() { } // and
var foo = new function() { }
Is the second one also a constructor expression? And if it is, of which class (I am at a loss of words here, I know JavaScript does not have classes, but by class, here, I mean template or function or prototype)
Update
Those who have provided links to related questions, thank you very much. I really appreciate it. I am trying to learn this language and at this point, honestly, I am so nascent in my judgement that I cannot tell if they're all the same question. I do know that the more I read, although I find it all very fascinating, the more it confuses me at this stage. I will probably take time to fully understand the beauty of this wonderful language. Meanwhile, please do keep mentioning other related threads.
This
var foo = function() { }
instantiates a function and assigns to foo a reference to that function.
This
var foo = new function() { }
instantiates a function, calls it with a new object as its context, and assigns the newly-created object (or the object return value from the function) as the value of foo. The function itself is discarded unless it by some means manages to return itself.
The second piece of code is, or should be, fairly rare in code not written by a confused person.
A Function Expression defines a function as a part of a larger expression syntax (typically a variable assignment ). Functions defined via Functions Expressions can be named or anonymous.
The following are examples of function expression that create a function and assign to the variable foo:
var foo = function() { }
var foo = function foo() { }
When you use the new keyword it does not create a function, it just creates an object and assigns it to the variable foo, the instantiated function gets called as well.
var foo = new function() { }

Javascript convert string into function name [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Call a JavaScript function name using a string?
javascript string to variable
I have this code:
var Functionify = function() {
return {
init: function(el, t) {
var els = document.getElementsByClassName(el);
var elsL = els.length;
while(elsL--){
//els[elsL].onclick = els[elsL].getAttribute(t);
els[elsL].addEventListener('click', els[elsL].getAttribute(t), false);
}
}
};
}();
Where el = 'myClassName' and t = 'data-id'
Now, 't' is a string, how can tell the addEventListener function to use 't' (a string) as a function name?
In the global namespace, you would do something like:
this.test = function() {
alert('test');
}
window['test']();
The better option however would be to make your function a method of an object you create rather than of the global window object.
I am not sure why you would do it, put if the function is part of the global scope you can use bracket notation.
window["stringName"]();
Using eval() is considered "evil", especially in the example given by Danila -- any piece of JS will / can be executed within an eval(). The best option as stated by epascarello, is to use square-bracket notation to invoke a named function. It should be noted, however, that windowt will invoke a function in the global namespace -- if the function is the method of an object, you should reference it as such.
Use eval() function
Example:
a = "alert(1)"
eval(a)

Why are there two different ways to create functions in Javascript?

In my code I have the following:
var setTheme = function (color) {
};
function setTheme(color) {
};
The function names are not really the same but I have put the same here. Is there a difference in the two ways of creating a function?
There is a difference. With a function definition, the entire definition is hoisted:
foo(5); // Pops up 5
function foo(n) {
alert(n);
}
Whereas with var, the declaration is hoisted but the assignment is not:
foo(5); // Error!
var foo = function(n) {
alert(n);
};
Another difference I noticed is that on Google Chrome Canary (currently and at least, I haven't tried in many other browsers) in ECMAScript 5 strict mode, a function definition cannot be nested more than one level deep:
!function() {
'use strict';
function Blah() {
function Lol() { // Error.
}
}
}();
So,
JS function for get set
var setTheme = function (color) {
};
If you need a private utility for getting/setting/deleting model values then you can declare a function as a variable like this. This could be useful for assigning a variable upon declaration calculated by a function.
For: simple version
function setTheme(color) {
};
This is the simplest way to declare a function in JavaScript. Say for example, we want to write a simple function called setTheme(color) which simply takes in one parameter color, does a simple color on the object or returns the value. Here are a few ways you might go about doing exactly this.
5 Different ways: interesting read:
http://www.jquery4u.com/jquery-functions/5-ways-declare-functions-jquery/
This has been answered many times. There are many ways to call these. As I understand, the first one is a function assignment, the second one is a function declaration. The first one will hoist setTheme to the top of the closest scope but it won't be defined as a function till it gets where it's actually assigned. The second one will hoist the function setTheme up top so you'll be able to use this function even before it's been declared. IMO, use always the first one.

Javascript function declaration. When to use what? [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Javascript: var functionName = function() {} vs function functionName() {}
What is the reason you would do:
somename = function(param1, param2) { }
In stead of doing:
function somename(param1, param2) { }
Well since the 1st syntax is a variable declaration and the 2nd is an actual function declaration, i would stick to the 2nd unless I truly needed the 1st.
Try to read up on scoping and variable hoisting and you will see that the 2nd syntax can sometimes create trouble for you :)
http://www.dustindiaz.com/javascript-function-declaration-ambiguity/
http://www.adequatelygood.com/2010/2/JavaScript-Scoping-and-Hoisting
Btw, you might want to browser this thread and look for more good stuff:
var functionName = function() {} vs function functionName() {}
$fn = function(param1, param2)
By using the above form you are able to pass $fn to any function as a parameter, or you could create a new object from that:
function doSomethingWithFn($fn);
or
$fnObject = new $fn(param1, param2)
You can use the second form when you just need a utility function, or for closures:
function utilityFn(str) {
return str.indexOf('a')
}
var str = utilityFn('abc');
or
$('#element').click(function() {
utiliyFn($('#element').html())
})
The first method creates a function object that you can then pass as parameter to other functions. For example, if you want to execute some code when a text box value changes, you can set a callback like this (using jQuery):
var onChange = function() { /* ... */ }
$("#username").change(onChange);

Javascript object creation best practice [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 7 years ago.
Improve this question
I have the following javascript :
var MyObject = (function() {
function Setup(args) {
this.prop1 = args.x;
this.prop2 = args.y
this.prop3 = this.prop1 + this.prop2;
this.Create = function() {
return 'a' + helperFunc();
}
function helperFunc() {
return this.prop3;
}
}
return {
init : function(args) {
var setup = new Setup(args);
setup.Create();
}
}
})();
$(function() {
MyObject.init(someArgs);
});
Is my approach to object construction a good practice?
I am getting undefined in the helperFunc when trying to access this.prop3.
I have also tried to assign this.prop1 + this.prop2 to a local variable and use a function to return this value like so:
function Setup(args) {
var total;
this.prop1 = args.x;
this.prop2 = args.y
total = this.prop1 + this.prop2;
this.getTotal = function() {
return total;
};
this.prop3 = this.prop1 + this.prop2;
...
...and when calling this in the helperFunc like this:
return this.getTotal();
.. i get this.getTotal is not a function
I have been reading around object creation and using closures to mimic private members and so on and since there is no one way to define objects I am getting confused.
TBH - I don't really understand the construct:
var myObject = (function() { ... } ();
I've seen it used a lot in jQuery plugins but what does the first parenth followed by empty parenth at the end mean and do?
Any knowledge imparted would be much appreciated.
Also, I have on order the Douglas Crockford book on javascript and until it arrives I need to try to solve this problem
To cite Xhalent's wonderful article (really well done and clearly wirtten) mentioned by him:
That is because the value of “this” is
different to the value of “this” when
the object was created.
So in your case:
...
var _this = this.prop3;
function helperFunc() {
return _this;
}
...
might achieve what's desired.
I've done a series on basic javascript fundamentals - objects and prototypes are covered here:
Javascript Object Instantation and Prototypes
I delve into Closures here:Javascript Closures
Hope they help. Cheers.
If you have a function that uses this, you must make sure that the calling context is correct. i.e. use this.helperFunc(), not just helperFunc() (but you'll also need to set things up so that this.helperFunc is defined). The referent of this inside helperFunc in your example is not the same as it is in Create().
You can think of it as though functions are not defined as members of objects, but called as members of objects.
There are three things that this might resolve to, depending on context.
A newly created object, if the function call was preceded by the new keyword.
The Object to the left of the dot when the function was called.
The Global Object (window), if neither of the above are provided.
If a function is called without an object, as in the case of your call to helperFunc in this.Create, this will be bound to the global object (window, when used in a browser)
Given something like this:
var o = {someVal:"hello"};
o.doSomething = function (){alert(this.someVal)};
Calling o.doSomething() will obviously alert "hello".
Given:
var o2 = {someVal:"world"};
o2.someFunc = o.doSomething;
Calling o2.someFunc() will alert "world", not "hello", as you would expect if it were a pointer to the doSomething member of o.
And given:
var someFunc = o.doSomething
someVal = "sailor"
Calling someFunc() will alert "sailor".
Another point of confusion is the use of this directly within Setup(). When you call a function using new, as you have done, this is not bound to the global object, but to a new instance of the Setup object.
For my example above, this means that calling new o.doSomething() will alert "undefined", as the new object that has been created for the call does not have a "someVal" member.
You have a good tutorial by Mike Koss on OOP in JS on this page.
I've seen it used a lot in jQuery
plugins but what does the first
parenth followed by empty parenth at
the end mean and do?
The second set of parenth immediatly invokes the function you have declared in the first set of parenth.
You could declare it and execute it separatly (allows to execute multiple times):
var myFunction = function() { alert("boo"); }; // Declare & instanciate
myFunction(); // Invoke
myFunction(); // Invoke again
Or do both in one line:
(function() { alert("boo"); })(); // Can only invoke now, the function is anonymous and not stored anywhere.

Categories