This question already has answers here:
Calling a function that's defined inside a function
(3 answers)
Closed 8 years ago.
I have the next in JS:
function doC() {
this.try = document.getElementById("try");
function tryC(){
//do something
}
}
Now, I want to call tryC function, when so I wrote the next:
<script type="text/javascript" src="myFile.js"></script>
<script type="text/javascript">tryC();</script>
But as I see, nothing happen. Ho I call tryC()?
You have defined C in the scope of doC. It is not accessible outside of doC.
If you want it to be accessible globally, then you have to explicitly assign it a global.
window.C = function () { /* etc */ };
Creating globals is usually a bad idea, more so when they aren't created at load time. There is probably a better way to achieve whatever problem you are trying to solve with this.
Your tryC is defined inside doC, it's not exposed (it's private), you can do:
function doC() {
this.try = document.getElementById("try");
return function(){
alert('Try C');
}
}
doC()(); // alerts
or
function doC() {
this.try = document.getElementById("try");
return {
tryC : function(){
alert('Try C');
}
}
}
doc().tryC(); //alerts
Or your way (globals all around)
function doC() {
this.try = document.getElementById("try");
this.tryC = function(){
alert('Try C');
}
}
doC(); // call first!
tryC(); // alerts
Related
This question already has answers here:
Return all of the functions that are defined in a Javascript file
(4 answers)
Closed 3 years ago.
I have a javascript file and in that there are some functions defined in it.
How can i get all the function name defined in that particular js file in an array of string
function getabc1() {
//block of code
}
function getabc2() {
//block of code
}
function getabc3() {
//block of code
}
function getabc4() {
//block of code
}
function getabc5() {
//block of code
}
function getabc6() {
//block of code
}
function getabc7() {
//block of code
}
I need all the 7 functions defined in this particular js file.
Only name of function
It will be great help if someone can help me on this.
You're just gonna inspect the code a little bit, answers in Stackoverflow aren't always meant to give you the exact thing you need. You should learn to derive from it. Looking at the link #AndroidNoobie said, all you had to do is push the key instead of the entire iterated value.
As stated on https://stackoverflow.com/a/11279959/7325182:
Declare it in a pseudo namespace
var MyNamespace = function(){
function getAllFunctions(){
var myfunctions = [];
for (var l in this){
if (this.hasOwnProperty(l) &&
this[l] instanceof Function &&
!/myfunctions/i.test(l)){
myfunctions.push(l);
}
}
return myfunctions;
}
function foo(){
//method body goes here
}
function bar(){
//method body goes here
}
function baz(){
//method body goes here
}
return { getAllFunctions: getAllFunctions
,foo: foo
,bar: bar
,baz: baz };
}();
//usage
var allfns = MyNamespace.getAllFunctions();
console.log(allfns)
//=> allfns is now an array of functions.
// You can run allfns[0]() for example
This question already has answers here:
What is 'Currying'?
(23 answers)
Closed 4 years ago.
I recently found JavaScript code like this:
someFunction()()
Function immediately invoked right after function without classic IIFE syntax.
What is that kind of syntax called? And how it works?
Its a function that returns another function.
Here is an example on how it works, this can help you to understand better.
function sum(x){
return function(y){
return x+y;
}
}
sum(3)(5); //8
For you code to work:
someFunction()();
You need to have code that looks like this:
function someFunction() {
console.log('someFunction()');
// do something before return
return function() {
console.log('someFunction()()');
// do something else here
}
}
someFunction()();
In this example you first call someFunction then you call the function that was returned by someFunction.
This can be good to do when you need to pass in a variable that will be used in the inner function but the inner function will be called in the future like this:
function someFunction(outerVal) {
console.log('Outer called.');
return function(innerVal) {
console.log('inner called.');
return outerVal * innerVal;
}
}
var inner = someFunction(12);
setTimeout(()=> {
console.log(inner(4));
}, 1000);
I use this often in Node.js for common middle-ware that needs a single value to be unique.
app.get('/dogs', myFn('woof'));
app.get('/cats', myFn('meow'));
app.get('/birds', myFn('tweet'));
function myFn(word) {
return function(req, res, next) {
res.write(word).end();
}
}
That is an over simplification, but can be vary powerful.
Just wondering if there is anyway to fire some code when a function is called, without adding the code to the function, for example:
function doSomething(){
//Do something
}
//Code to call when doSomething is called
You can wrap the function :
(function(){
var oldFunction = doSomething;
doSomething = function(){
// do something else
oldFunction.apply(this, arguments);
}
})();
I use an IIFE here just to avoid polluting the global namespace, it's accessory.
Well, yes, it's not actually hard to do. The crucial thing is that a function's name is just an identifier like any other. You can redefine it if you want to.
var oldFn = doSomething;
doSomething = function() {
// code to run before the old function
return oldFn.apply(this, arguments);
// code to run after the old function
};
NB that it's better to do oldFn.apply(this, arguments) rather than just oldFn. In many cases it won't matter, but it's possible that the context (i.e. the value of this inside the function) and the arguments are important. Using apply means they are passed on as if oldFn had been called directly.
What about something like:
function doSomething(){
doSomething.called = true;
}
//call?
doSomething();
if(doSomething.called) {
//Code to call when doSomething is called
}
I know you said you don't want to modify the original function, but consider adding a callback. Then you can execute code based on different results in your function (such as onSucess and onError):
function doSomething(onSuccess, onError){
try {
throw "this is an error";
if(onSuccess) {
onSuccess();
}
} catch(err) {
if(onError) {
onError(err);
}
}
}
Then, when you call doSomething, you can specify what you want done with inline functions:
doSomething(function() {
console.log("doSomething() success");
}, function(err) {
console.log("doSomething() error: " + err);
});
This question already has answers here:
How can I pass a parameter to a setTimeout() callback?
(29 answers)
Closed 12 months ago.
function f1()
{
c = setTimeout(f2,200);
}
function f2()
{
//code
}
The above code is just fine. But what I want to ask that: can I use some argument in function f2() which is passed from the calling environment? That is:
function f1(v1)
{
c = setTimeout(f2(v1),200);
}
function f2(v2)
{
//code
}
Is it valid? Because I tried something like this,but the problem is that I am not able to clearTimeout by using variable c. I am not sure what to do.
Use Closure -
function f1(v1)
{
c = setTimeout(f2(v1), 200);
}
function f2(v2)
{
return function () {
// use v2 here, and put the rest of your
// callback code here.
}
}
This way you will be able to pass as many arguments as you want.
Since you are declaring c as a global variable (which is bad), you can easily clear the timeout using -
clearTimeout(c);
If you are still not being able to clear the timeout, it only means that the duration has elapsed and your callback fired, or there is some error somewhere else. In that case, post your code that you are using to clear your timeout.
You can either use the function.bind method or you can simply wrap the invocation
function f1(v1) {
c = setTimeout(function() {
f2(v1);
}, 200);
}
var timeout;
// Call `f2` with all arguments that was passed to the `f1`
function f1 () {
var args = arguments;
timeout = setTimeout(function () { f2.apply(this, args) }, 200);
}
Or in this way:
// Call `f2` with some params from `f1`
function f1 (v1) {
timeout = setTimeout(function () { f2(v1) }, 200);
}
Answer to your question: you couldn't clear the timeout because you execute function immediately.
I haven't found a good reference for declaring my own functions inside the
jquery.ready(function(){});
I want to declare them so they are inside the same scope of the ready closure. I don't want to clutter the global js namespace so I don't want them declared outside of the ready closure because they will be specific to just the code inside.
So how does one declare such a function...and I'm not referring to a custom jquery extension method/function...just a regular 'ol function that does something trivial say like:
function multiple( a, b ){
return a * b;
}
I want to follow the jquery recommendation and function declaration syntax. I can get it to work by just declaring a function like the multiply one above...but it doesn't look correct to me for some reason so I guess I just need some guidance.
I believe that you would be okay just declaring the function inside the ready() closure, but here you can be a bit more explicit about the local scoping:
jQuery.ready(function() {
var myFunc = function() {
// do some stuff here
};
myFunc();
});
It might sound simple but you just ... declare the function. Javascript allows functions to have inner functions.
$(document).ready( function() {
alert("hello! document is ready!");
function multiply(a, b) {
return a * b;
}
alert("3 times 5 is " + multiply(3, 5));
});
I have a StartUp function, and I use it as printed bellow:
function StartUp(runnable)
{
$(document).ready(runnable.run);
}
var ExternalLinks =
{
run: function()
{
$('a[rel="external"]').bind('click', ExternalLinks.click);
},
click: function(event)
{
open(this.href);
return false;
}
}
StartUp(ExternalLinks);
var ConfirmLinks =
{
run: function()
{
$('a.confirm').bind('click', ConfirmLinks.click);
},
click: function(event)
{
if (!confirm(this.title)) {
return false;
}
}
}
StartUp(ConfirmLinks);
My web sites are modular, so every module has N actions and every action can have a .js file, so I just write function and call it with StartUp(...functionName...)