Why does this not work:
$(document).on('click','a',myFunction);
var myFunction = function() {
debugger;
}
When this does:
$(document).on('click','a',function() {
debugger;
}
I've started to learn more by naming all my anonymous functions and breaking them out into their own separate named functions.
You have to swap the lines:
var myFunction = function() {
debugger;
}
$(document).on('click','a', myFunction);
Otherwise, you would be assigning undefined as the event handler, as the variable myFunction doesn't have a value yet when you were passing it to .on.
Also: assigning a function to a variable like that doesn't make it named, it's still an anonymous function, just stored in a variable. A named function would be:
var myFunction = function someName() {
debugger;
}
See Named function expressions demystified for more details.
Instead of saying:
var myFunction = function() {
debugger;
}
you need to say:
function myFunction() {
debugger;
}
This will declare the function on the first pass so that it can be referenced during program execution.
Related
If I pass function to a function with same function name and handler name, which one will get precedence ? and how to access each of those two inside function in case in need to do recursion as well as refer to the passed function. See below code.
var f1,f2;
(function f(f){
return typeof f(f2); /*please check below comments for output of this line*/
})(function(f1){ return 1; });
/* this will call the passed function,why not recursion will not happen here? */
The function parameter gets precedence over the function's own name. If you shadow or overwrite a variable, you can't access it (unless it's a shadowed global).
Solution is to use different names.
The recursion doesn't happen simply because the argument of the function get precendence than the function itself. here is an example that shows it:
(function f (f) {
return f.name;
}) (function funcName () { }); // this will return funcName
if we change the name of the argument to f1, f will become the reference of the function itself
(function f (f1) {
return f.name;
}) (function funcName () { }); // this will return f
I see that you use jquery. So I want to ask where do you have declared your functions? inside
<script type="text/javascript">
$(document).ready(function(){
function f(){
return 'this is local function inside anonymous function, so it's invisible for recursion in aside of current document ready'
}
});
//or here?
function f(){
return 'this function is a window object property, and must be visible for recursion';
}
</script>
When I run the following code, the alert messages shows up but this.test() does not run.
function SomeFunction() {
document.onclick = function(e) {
alert("Hi");
this.test();
};
}
SomeFunction.prototype.test = function (){
...
}
However when I try this:
function SomeFunction() {
document.onclick = this.test();
}
SomeFunction.prototype.test = function (){
...
}
this.test() will run.
EDIT: I have added more details to my code.
Your issue is related to scope. Try:
document.onclick = function(e) {
alert("Hi");
test();
};
this will vary depending upon where it is called from. In your first example, you are calling it from within an anonymous function and therefore the scope of this shifts to inside that function. In the second example, the scope is a level higher and refers to your SomeFunction() function.
Since your function is nested inside another function, you may want to reassign this to a another variable that is accessible up the scope chain. E.g.
function SomeFunction() {
that = this;
document.onclick = function(e) {
alert("Hi");
that.test();
};
}
In the first example, the word "this" refers to function itself. So the function test would be outside its scope.
But on the second one you are telling the code that this.test() is the actual onclick function, that is why it's working there and not on the first one.
I declared two functions using function expression innerone and innertwo. I first declared innerone and after that innertwo. Inside innerone I am calling innertwo function. But my concern is that I am declaring innertwo after innerone using function expression which means innertwo is not hoisted. So why these functions work in this order? Is it mandatory to change their order?
Here is code
var one = function () {
var innerone = function () {
innertwo();
},
innertwo = function () {
console.log('innertwo');
};
return {
innerone: innerone
};
};
var o = new one();
o.innerone();
It's working because innerone is called only when you call it. And by the time it's called innertwo is defined.
You asked in your comment for simpler ways to write this code, so here are a couple simpler ways. The first still returns the structure and can be just called as a function without new. The second adds a property to the function object, but still preserves the private function innertwo(). The second option looks the cleanest to me.
Option 1:
function one() {
function innertwo() {
console.log('innertwo');
}
return {
innerone: function() {
innertwo();
}
};
}
var o = one(); // new is not needed here
o.innerone();
Option 2:
function one() {
function innertwo() {
console.log('innertwo');
}
this.innerone = function () {
innertwo();
};
};
var o = new one();
o.innerone();
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();
Are the JavaScript code snippets given below some sort of function declaration? If not can someone please give an overview of what they are?
some_func = function(value) {
// some code here
}
and
show:function(value){
// some code here
}
There are six ways/contexts in which to create functions:
1) Standard declarative notation (most familiar to people with C background)
function foo() {}
All the rest are function expressions:
2) As a method of an object literal
var obj = {
foo: function() {}
};
3) As a method of an instantiated object (created each time new is exectued)
var Obj = function() {
this.foo = function() {};
};
4) As a method of a prototype (created only once, regardless of how many times new is executed)
var Obj = function() {};
Obj.prototype.foo = function() {};
5) As an anonymous function with a reference (same effect as #1) *
var foo = function() {};
6) As an immediately executed anonymous function (completely anonymous)
(function() {})();
* When I look at this statement, I consider the result. As such, I don't really consider these as anonymous, because a reference is immediately created to the function and is therefore no longer anonymous. But it's all the same to most people.
The first one is simply creating an anonymous function and assigning it to a variable some_func. So using some_func() will call the function.
The second one should be part of an object notation
var obj = {
show:function(value){
// some code here
}
};
So, obj.show() will call the function
In both cases, you are creating an anonymous function. But in the first case, you are simply assigning it to a variable. Whereas in the second case you are assigning it as a member of an object (possibly among many others).
First is local (or global) variable with assigned anonymous function.
var some_name = function(val) {};
some_name(42);
Second is property of some object (or function with label in front of it) with assigned anonymous function.
var obj = {
show: function(val) {},
// ...
};
obj.show(42);
Functions are first-class citizens in JavaScript, so you could assign them to variables and call those functions from variable.
You can even declare function with other name than variable which that function will be assigned to. It is handy when you want to define recursive methods, for example instead of this:
var obj = {
show: function(val) {
if (val > 0) { this.show(val-1); }
print(val);
}
};
you could write:
var obj = {
show: function f(val) {
if (val > 0) { f(val-1); }
print(val);
}
};
One way of doing it:
var some_func = function(value) {
// some code here
}
Another way:
function some_funct() {
}
Yet another way:
var some_object={};
some_object["some_func"] = function() {};
or:
var some_object={};
some_object.some_func = function() {};
In other words, they are many ways to declare a function in JS.
Your second example is not correct.
The first one is a function declaration assigned to a variable (at least it should be, despite the fact that it's missing the variable type declaration first), the second one is probably related to a object declaration.
They are called anonymous functions; you can read more about them here:
http://www.ejball.com/EdAtWork/2005/03/28/JavaScriptAnonymousFunctions.aspx
The first example creates a global variable (if a local variable of that name doesn't already exist) called some_func, and assigns a function to it, so that some_func() may be invoked.
The second example is a function declaration inside an object. it assigns a function as the value of the show property of an object:
var myObj = {
propString: "abc",
propFunction: function() { alert('test'); }
};
myObj.propFunction();
The first one...
some_func = function(value) {
// some code here
}
is declaring a variable and assigned an anonymous function to it, which is equivalent to...
function some_func (value) {
// some code here
}
The second one should look like this...
obj = {
show:function(value){
// some code here
}
}
// obj.show(value)
and equivalent to...
//pseudo code
class MyClass {
function show (value) {
// some code here
}
}
obj = new MyClass(); // obj.show(value)
Cheers