How do I call a function defined in a javascript variable - javascript

I have a function defined in a javascript variable. How do I call that function within a javascript function?
function clear_viewer() {
var stop_function = "jwplayer.stop();";
// call stop_function here
}
Thanks.

function clear_viewer() {
var stop_function = "jwplayer.stop();";
eval(stop_function);
}
You shouldn't do this though, eval should be avoided if at all possible. Instead you should do something more like this, which creates a function directly for later execution.
function clear_viewer() {
var stop_function = function() {
jwplayer.stop();
};
stop_function();
}

Could always go with the 'all evil' eval():
eval(stop_function);
Obviously you need to be very careful when using eval so that you don't wind up executing malicious code accidentally. Another option would be to turn stop_function into an anonymous function that executes your code:
var stop_function = function(){
jwplayer.stop();
};
stop_function();

function clear_viewer() {
var stop_function = function(){ jwplayer.stop();};
stop_function();
}

Related

JS function inside function:

Can i do smth like this?
function calltime(gmt,ajaxfile){
//do something with vars gmt & ajaxfile...
function (){
alert(gmt+ajaxfile);
}
}
as you may notice I want the inner function without a name to use arguments of a parent without sending them directly as arguments, Is it possible or is there the other way (without creating completely separate function)?
function calltime(gmt,ajaxfile){
//do something with vars gmt & ajaxfile...
return function (){
alert(gmt+ajaxfile);
}
}
//you can call like this
calltime('Hello', 'there')();
//you can call like this also
var callit = calltime('Hello', 'there');
callit();
If you are creating a function inside a function you are creating a clouser. so that you can access that inner function later and you can use outer function arguments and variables(scope) in the inner functions whenever you want. so you no need to pass argument to the inner function.
Here's one way to get it to work. These methods will have self invoking inside. If you don't want them to invoke when calling calltime, then you can look at #harry's answer, which returns the inner function instead of invoking it.
var calltime = function(gmt, ajaxfile) {
(function (g, a){
alert(g + a);
})(gmt, ajaxfile);
};
calltime('Hello ', 'there');
But if you really don't want to specify arguments, you can just straight up do this:
var calltime = function(gmt, ajaxfile) {
(function (){
alert(gmt + ajaxfile);
})();
};
calltime('Hello ', 'there');
The inside function will self invoke itself. You can copy and paste this into chrome inspector to test.
And one more, since we're talking about self invocation, might as well invoke everything about your question!
(function calltime(gmt, ajaxfile) {
(function (){
alert(gmt + ajaxfile);
})();
})('Hello ', 'there');
Edit: one more version that takes in numerous arguments.
var calltime = function () {
(function () {
var args = Array.prototype.slice.call(arguments);
alert(args.join(' ')); // outputs 'hello there friend'
}).apply(this, arguments);
};
calltime('hello', 'there', 'friend');
function calltime(gmt,ajaxfile){
//do something with vars gmt & ajaxfile...
var a = function (){
alert(gmt+ajaxfile);
}
}
calltime('a','b');
You can do it like so.

Make a function run once by redefining

I've found myself using this pattern recently to do initialization that should only ever run once:
function myInit() {
// do some initialization routines
myInit = function () {return;};
}
This way if I had two different methods which required something myInit did, it would ensure that it would only run once. See:
function optionA() { myInit(); doA(); }
function optionB() { myInit(); doB(); }
In the back of my head I feel like I'm missing something and I shouldn't be doing this. Is there any reasons why I shouldn't write code like this?
Is there any reasons why I shouldn't write code like this?
One reason is that the function will only work as you intend in the scope it was defined in. E.g. if you pass the function somewhere else, it won't be affected by your modifications and in the worst case would create an implicit global variable. E.g.
function myInit() {
// do some initialization routines
myInit = function () {return;};
}
function foo(init) {
init();
init();
}
foo(myInit);
The better approach is to encapsulate the whole logic:
var myInit = (function() {
var initialized = false;
return function() {
if (initialized) return;
initialized = true;
// do some initialization routines
};
}());
Now, no matter how, where and when you call myInit, it will do the initialization step only once.
May be you can do something like,
var myInitCalled = false; // Global declaration of flag variable
function myInit() {
// do some initialization routines
myInitCalled = true; // Setting the global variable as true if the method is executed
myInit = function () {return;};
}
Then in your methods, you can probably use:
function optionA()
{
if(!myInitCalled ) // Checking if first time this is called.
{myInit();}
doA();
}
function optionB()
{
if(!myInitCalled )
{myInit();}
doB();
}
This will ensure that myInit is called only once!!

how to use window.setTimeout with javascript and the module pattern

i have this example:
var myApp = (function() {
var inputClick = function() {
console.log('inputClick');
};
var loadRecentTimeout = function()
{
window.setTimeout("inputClick()",3000);
};
return {
loadRecentTimeout:loadRecentTimeout,
inputClick:inputClick
};
})();
myApp.loadRecentTimeout(); // this returns inputClick() undefined
window.setTimeout("myApp.inputClick();",3000); // this one seems to work , but it calls that method only one time and not every 3 seconds
can anyone explain how can i make this code call the inputClick() method every 3 seconds?
thanks
You want to call setInterval instead of setTimeout
var eventInterval = window.setInterval(function () {
myApp.inputClick();
},3000);
You also should pass your function as a function instead of a string.
If you need to cancel your repeating event you can call clearInterval
clearInterval(eventInterval)
When you use a string "functionName()" it evals it in window scope. Instead, assign a reference to the function with just using the name. setTimeout only fires once, you want to use a setInterval.
var myApp = (function() {
var inputClick = function() {
console.log('inputClick');
};
var loadRecentTimeout = function()
{
window.setInterval(inputClick,3000);
};
return {
loadRecentTimeout:loadRecentTimeout,
inputClick:inputClick
};
})();

Noob javascript, why is this firing onload?

So I dont understand why the console logs 1 right away onload or something when i have one.onclick = alterIt(1) shouldn't it wait till i click one. Anyway, obviously I am not ver good at javascript, thanks for your help.
window.onload = initialize;
function initialize() {
if (1 == 1){
calculation();
}
}
function calculation() {
var one = document.getElementById('one');
one.onclick = alterIt(1);
}
function alterIt(x) {
console.log(x);
}
When you wrote:
one.onclick = alterIt(1);
...then you invoked the alterIt function and set the return value as the onclick handler. Instead, you wanted:
one.onclick = function(){ alterIt(1) };
// ...or better yet
one.addEventListener('click',function(){ alterIt(1) },false);
When the line one.onclick = alterIt(1); is executed, alterIt(1) is actually evaluated. What you want is to bind a function to one.onclick, which is only executed when the onclick event fires. You need something like
one.onclick = function() { alterIt(1) };
which doesn't bind the result of alterIt(1) to one.onclick, but rather the result of the function evaluation.
Wrap the function call like this so it doesn't fire until click:
window.onload = initialize;
function initialize() {
if (1 == 1){
calculation();
}
}
function calculation() {
var one = document.getElementById('one');
one.onclick = function(){ alterIt(1);};
}
function alterIt(x) {
console.log(x);
}
Example fiddle: http://jsfiddle.net/RkH6Q/
There are two ways that you could code to work around this issue:
//Anonymous Closures
one.onclick = function(){ alterIt(1); };
//Bind Closures
one.onclick = alertIt.bind(window, 1);
Note: Function.bind() is supported by all the browsers for a year. If you care about old browsers, anonymous closures is the way to go.
What is happening is that you are calling the alterIt function when you should just be passing it in. So remove the parenthesis like so:
one.onclick = alterIt;

When should I put a semicolon after a function in javascript?

My examples:
(First example area is the function assignment with semicolon)
function makeImage() {
var canvas = document.getElementById("tshirtCanvas");
**canvas.onclick = function () {
window.location = canvas.toDataURL('image/png');
};**
}
vs
window.onload = function() {
var button = document.getElementById("previewButton");
button.onclick = previewHandler;
makeImage();
}
I thought I had the hang of when to use it, and when not to, but I guess I do not. Thanks.
You should put a semi-colon after a function when you use it as a value:
var fn = function () {};
blarg.fn = function () {};
doStuffWith(function () {});
If you're just declaring a named function by itself, you don't need the semicolon:
function doFoo() {}
Note that in the top cases, you don't always have to have a semicolon, but you should put one anyway.
Function expressions get semicolons (normal line ending rules apply). Function declarations do not.
http://javascriptweblog.wordpress.com/2010/07/06/function-declarations-vs-function-expressions/
Your function declaration doesn't need it after. Just if you are calling it.
function doThis(args){
getterMethod(args);
}
If you are assigning a function to a property, you should put a semicolon.
So you could put a semicolon for the window.onload because you are assigning a function to the onload property of the window. The semicolon isn't required, but I highly recommended you put it to prevent confusion.
window.onload = function() {
init();
doSomethingElse();
};
From the MDN Docs.

Categories

Resources