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

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
}

Related

Double function name in javascript [duplicate]

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);

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

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.

How would I 'wrap' an object and replace all of the functions in it? [duplicate]

This question already has answers here:
JavaScript closure inside loops – simple practical example
(44 answers)
Is there a way to wrap all JavaScript methods with a function?
(3 answers)
Closed 8 years ago.
Here's what I want to achieve:
var obj = {
something: 1,
someFunction: function () {
return 'hello';
}
};
wrap(obj).someFunction('hello'); // this should be different from obj.someFunction defined above
wrap(obj).something = 2; // this should still work
Basically, I want to 'wrap' an object and replace all the functions in it with something else.
Here's how I've defined the wrap function:
function hello (v) {
return 'Hello ' + v;
}
function wrap (oldObj) {
var newObj = {};
for (var k in oldObj)
Object.defineProperty(newObj, k, {
get: function () {
if (typeof oldObj[k] === 'function')
return hello;
return oldObj[k];
},
set: function (val) {
oldObj[k] = val;
}
});
return newObj;
}
(hello is just an example replacement function)
When I try to use this, everything in obj gets replaced with a function (i.e even obj.something, which was set to 1, is replaced with a function). I can't seem to find any issues with this code. I've tried debugging it and haven't found the issue yet.
What might be the issue? How else can I solve this problem?
Edit 1: I don't want to replace functions in the object itself, I want to create an entirely new object.

Prototyping functions coding style [duplicate]

This question already has answers here:
Javascript: Overwriting function's prototype - bad practice?
(6 answers)
Closed 8 years ago.
When protyping functions (in most code I've seen) they are generally written like so:
function MyFunc() { }
MyFunc.prototype.render1 = function() { };
MyFunc.prototype.render2 = function() { };
MyFunc.prototype.render3 = function() { };
However this can be shortened like so:
function MyFunc() { }
MyFunc.prototype = {
render1: function() { },
render2: function() { },
render3: function() { }
};
From my understanding the shortended way will completely override the functions prototyped properties, as opose to adding one. Is there any other downsides to writing the protoyped functions in this manner?
I don't know any issues writing the second way - which I use also - because root prototype is Object, and you are passing an object so...

More elegant way to call method from ajax callback function [duplicate]

This question already has answers here:
How to access the correct `this` inside a callback
(13 answers)
Closed 8 years ago.
I have a problem with javascript namespaces.
I want to call secondMethod from ajax callback function but I don't know how to get reference to it.
I have done it like that yet. But variable thisReference seems to me awkward. And whole construction is difficult to read.
So I'm writing there for help and answer how to rewrite it better.
var testObject = new TestObject();
testObject.firstMethod("hello world!");
function TestObject() {
var thisReference = this;
this.firstMethod = function(firstParam) {
ajaxFunc(firstParam, function(ajaxResult) {
thisReference.secondMethod(ajaxResult);
});
};
this.secondMethod = function(secondParam) {
alert("secondMethod " + secondParam);
};
}
function ajaxFunc(hello, callBack) {
callBack(hello);
}
Thanks a lot.
Ondra
Something like what you're doing is a common way to do it. Using:
var that = this;
or:
var self = this;
are common names to keep a hold of your original scope.
Another option (which I prefer) is to bind the this object to the method you're calling so that you have access to it in the callback. That would look like this:
this.firstMethod = function(firstParam) {
ajaxFunc(firstParam, function(ajaxResult) {
this.secondMethod(ajaxResult);
}.bind(this));
};
Hope that helps.

Categories