Execute private function inside the class by its name (string) - javascript

At the moment I have simple JavaScript class like this:
function MyClass() {
// ... some code ...
this.Create = function() {
funcName = 'myTestFunc()';
cTimer = setTimeout(funcName, 1000);
}
// ... more code ...
var myTestFunc = function() {
alert ('everything\'s OK!');
}
// ... more code ...
}
and to test it I'm using this code:
x = new MyClass();
x.Create();
I have some troubles to execute this function by it's name. If I put just eval(funcName); instead of setTimeout call it works fine but can't figure out why it doesn't work this way.
Course, this is part of more complex code but rest of code is irrelevant to this problem.
My question is obvious - How to execute function by its name set as setTimeout function's argument? Is it possible?
Note: Making this function public (this.myTestFunc = ...) isn't an option!
Update:
funcName = "myTestFunc()"; is just an example. In real code it looks like funcName = getRandomEffectFunctionName();! It's just a random value.

Referring to the update:
Instead of setting:
var funcName = "getRandomEffectFunctionNeme()";
Thus, setting a reference to the function's name you should do
var funcRef = getRandomEffectFunctionNeme;
And set a reference to the function itself . Not only this avoids the issues setTimeout with strings has*. It also solves your closure issue since your code is structured in such a way the timeout has access to the function itself.
In your case, let's assume you have some functions that are filters, for example lowPass highPass and blur. In that case, instead of choosing a function name we would be choosing a function.
First, we store these functions in an array:
var filters = [lowPass,highPass,blur];
In JavaScript, functions are first-class objects, you can pass them around just like other objects.
Next, we'll get a random number
var chosen = Math.floor(Math.random()*3);//get a random number between 0 and 2
Finally, we'll choose the filter and invoke it
var filter = filters[chosen];
setTimeout(filter,1000);
( * just try debugging it, it basically invokes the compiler whenever ran and is painfully slow)
You just pass a function to setTimeout as a parameter, rather then a string, setTimeout(myTestFunc,1000) .
When calling Create it would have access to it anyway because they are in the same closure.

NOTE: This solution is only applicable if you can not pass the function name as a function reference, for example if you're integrating with code that is outside your control. Generally, when possible, you should pass a function reference since in JavaScript, all functions are objects.
Assuming that the timeout and the function are in the same closure your code is pretty close. The problem is that your eval call executes in the global context because it is in a timer. This means they are no longer in the same lexical scope.
You can however, grab a reference to the function by clever use of eval which you can later call in the setTimeout invocation.
var F=eval(funcName);// gain a reference to the function given the function's name
cTimer = setTimeout(F, 1000);
If you're using AIR or don't trust the functionName string you can do the following:
function Test(){
var functionContainer={
t:function(){
console.log("it's t");
}
};
this.callT=function(functionName){
var F=functionContainer[functionName];
console.log("F is:",F);
setTimeout(F,500);
}
}
(new Test()).call("t");
This is preferable since you are invoking setTimeout with a function's name and not a string. In general, using setTimeout with a string can have issues, it's hard to debug or maintain.

Related

assigning a function(with arguments) a variable name? [JavaScript]

I've decided to teach myself functional programming.
I've submitted all of my assignments whilst maintaining the rules of functional programming, and my instructor is totally fine with it. To grab inputs, I've been doing something like this:
var getWidth = function(){
return prompt("What is the width?");
};
This works fine but it could be something simpler, like:
var getWidth = prompt("What is the Width?");
The problem with this, is when I call the function getWidth(), it simply runs the function once and assigns it to the getWidth variable. But that's not what I want, I want it to run prompt("What is the Width?") every time getWidth() is called. I've tried to search for it, but I'm not really entirely sure how to phrase it. Google's useful, if you know how to use it.
Well you could use bind()
var hm = window.prompt.bind(window, "simpler?");
console.log(hm());
it could be something simpler, like:
You cannot "simplify" a function
var a = function onePlusTwo() {
return 1 + 2;
};
by writing
var a = 1 + 2;
The two do entirely different things.
The first defines a function (meaning, does not execute it), and assigns the function to the variable a. The function can then be called with a(), which will evaluate to 3, since that is the return value of the function:
alert(a() * 2) // 6
The second (var a = 1 + 2;) merely executes the code which you had in the body of the function. Executing it assigns the result of 1 + 2 to the variable a. This code is "re-usable" only by copying and pasting it elsewhere in your program.
So if you want to define functionality and re-use it, you have no choice but to define it as a function. That's what functions are for!
If you want to take a function and make another function you can use to call that function later, with or without some arguments, then as mentioned in another answer, you can use bind, as in var a = prompt.bind(window, "What is the width?");, and then call it with a(). But this is essentially the same as writing the function out in the way you did in the first example, and is a little bit less readable.
By the way, none of this is "functional programming". Functional programming does not mean just using functions; all programs do that. Functional programming refers to a style of programming involving manipulating, combining, dynamically creating, and passing around functions.
You cannot simplify your function this way. By the first method:
var getWidth = function(){
return prompt("What is the width?");
};
You are returning an executable function, and assigned the function reference to a variable getWidth. However in the second one:
var getWidth = prompt("What is the Width?");
You are returning the result of the function window.prompt.
What the OP might be looking for, is the lambda functional shorthand. It's a really simple bit of code, that let's you right functions much shorter. It's usually, used for anonymous functions, but it could easily be re-purposed here. For example:
function getWidth(){
return prompt("What is the width?");
}
Would be reduced to:
var getWidth() = () => prompt("What is the width?");
Note that the value of prompt is returned automatically, so you don't need to add return to your code.
Parameters could also be specified if desired, like this:
var getWidth = (x) => prompt(x);
And if you use arguments this way, then the () are optional. This would work too:
var getWidth() = x => prompt(x);

Javascript function within return statement

I'm starting new with javascript and still learning. I came across this code with different function declaractions. What are the differences between funcA, funcB, and funcX? In the code funcA, funcB are used within the module, and funcX & funcY are called from outside the module as someModule.funcX(). Likely very simple but I don't know what this is called to even do a rearch. Any pointers will be appreciated.
var someModule = (function() {
var funcA = (function() {...})();
var funcB = function() {...};
return {
funcX: function(){...},
funcY: function(){...}
};
})();
If you just want the difference between all of the functions here is the difference.
First difference between funcA, funcB and funcX, funcY.
Whatever we have inside return statement will be accessible by someModule. So we can do both of these below
someModule.funcX();
someModule.funcY();
But we cannot do someModule.funcA() or someModule.funcB(). To understand why that we can do this is to understand how () this behaves.
Whatever expression is put inside brackets is executed and result is returned there. So in this example we have put a function inside these brackets, so an anonymous function will be created inside memory and it object will be returned here.
Now we have put one more pair of brackets after function declaration. So, what happens here is (returned function object)(). So this function will be called immediately and an object containing two properties funcX and funcY whose value are function will be returned.
Now moving to second part that is inside the function. Here the difference between funcA and funcB is that funcA is same as someModule i.e. it is also an IIFE and depending upon the body of funcA, it will be decided that if we are returning function object from inside the body of funcA, then it will also be a function otherwise it will contain whatever we return from inside of body of funcA.
Apart from that all other are simple functions.
Also, not related to what was asked. We can access funcA and funcB inside funcX and funcY, and even after containing function is executed then also we will still be able to access both of these function. For more details on this behavior look for closure in JavaScript. Happy learning JavaScript. :)
This is simply a module pattern.
The way this is written is very similar to the revealing module pattern.
Basically, you the function returns something (anything, really) which is meant to be the public interface to the module (note that by interface I do not mean one that needs to be implemented, merely that this is the endpoint to interact with the module, like an API).
The classical way to do this (as a revealing module pattern) would actually be:
var someModule = (function() {
var funcA = (function() {...})();
var funcB = function() {...};
var funcX = function(){...}
var funcY = function(){..}
return {
funcX: funcX,
funcY: funcY
};
})();
The reason this is called the revealing module pattern, is because you define your module and all private and public functions in the module, and in the end you reveal what you want to expose.
This makes it easy to understand what's happening inside and to change it if necessary.
A good resource to quickly learn about various module patterns is this site
Andrew,
So it's a little confusing, but it's pretty basic javascript weirdness.
You can save a function in a variable like this:
var a = function(){return 30}
Here a hold the function itself. You can then call this function with ():
a() // result is 30;
Alternatively I could forget the variable and just call the function by adding the () to the end:
(function(){return 30})();
this also results in 30, although we didn't assign it to anything.
So now if I assign that last one to a variable:
var b = (function(){return 30})();
Unlike a above, which holds the function itself, b holds the result, whatever that might be, of calling the function — b is 30 because the function is called and then the result is assigned to b.

use this.argu to store arguments a good practice?

i am new to front-end developing,and now i am reading a lot of js code written by other in my company and find they will use this syntax to store the arguments :
function func1(argu1,argu2){
this.argu1 = argu1;
this.argu2 = argu2;
// other code run here....
}
for me i usually skip this and use the argument directly in my code or get a variable for the n,like this:
function func2(argu1,argu2){
alert(argu1);
alert(argu2);
var arguOne = argu1,arguSec = argu2;
// other code run here...
}
so i want want to ask why use this syntax to store an arguments?
is this a good practice ?and why?
Have i ever miss some concepts that i should know?
see the fiddle, written by the my co-worker who has been no longer a front-ender....
In your first example, func1 can be used to create objects. It is effectively a class definition (constructor). It can be used as follows:
function func1(argu1,argu2)
{
this.argu1 = argu1;
this.argu2 = argu2;
}
var instance = new func1('a', 'b');
alert(instance.argu1);
alert(instance.argu2);
Lordy lord: Instead of defining the function, and calling it at the end, try using a closure. Just keep the function definition as is, but put it in brackets:
(function new_slider (arguments)
{
//your code here
})('#new_slider',1500,150,10);
This way, the function is declared, and invoked at the same time, all functions defined within the main new_slider function will have access to the arguments. There is absolutely no reason to use this.argu1 to store these values. If anything, it creates global variables, which is considered bad practice.
Please google closures in JavaScript, they're extremely powerful

Why is this function wrapped in parentheses, followed by parentheses? [duplicate]

This question already has answers here:
What is the (function() { } )() construct in JavaScript?
(28 answers)
Closed 9 years ago.
I see this all the time in javascript sources but i've never really found out the real reason this construct is used. Why is this needed?
(function() {
//stuff
})();
Why is this written like this? Why not just use stuff by itself and not in a function?
EDIT: i know this is defining an anonymous function and then calling it, but why?
This defines a function closure
This is used to create a function closure with private functionality and variables that aren't globally visible.
Consider the following code:
(function(){
var test = true;
})();
variable test is not visible anywhere else but within the function closure where it's defined.
What is a closure anyway?
Function closures make it possible for various scripts not to interfere with each other even though they define similarly named variables or private functions. Those privates are visible and accessible only within closure itself and not outside of it.
Check this code and read comments along with it:
// public part
var publicVar = 111;
var publicFunc = function(value) { alert(value); };
var publicObject = {
// no functions whatsoever
};
// closure part
(function(pubObj){
// private variables and functions
var closureVar = 222;
var closureFunc = function(value){
// call public func
publicFunc(value);
// alert private variable
alert(closureVar);
};
// add function to public object that accesses private functionality
pubObj.alertValues = closureFunc;
// mind the missing "var" which makes it a public variable
anotherPublic = 333;
})(publicObject);
// alert 111 & alert 222
publicObject.alertValues(publicVar);
// try to access varaibles
alert(publicVar); // alert 111
alert(anotherPublic); // alert 333
alert(typeof(closureVar)); // alert "undefined"
Here's a JSFiddle running code that displays data as indicated by comments in the upper code.
What it actually does?
As you already know this
creates a function:
function() { ... }
and immediately executes it:
(func)();
this function may or may not accept additional parameters.
jQuery plugins are usually defined this way, by defining a function with one parameter that plugin manipulates within:
(function(paramName){ ... })(jQuery);
But the main idea is still the same: define a function closure with private definitions that can't directly be used outside of it.
That construct is known as a self-executing anonymous function, which is actually not a very good name for it, here is what happens (and why the name is not a good one). This:
function abc() {
//stuff
}
Defines a function called abc, if we wanted an anonymous function (which is a very common pattern in javascript), it would be something along the lines of:
function() {
//stuff
}
But, if you have this you either need to associate it with a variable so you can call it (which would make it not-so-anonymous) or you need to execute it straight away. We can try to execute it straight away by doing this:
function() {
//stuff
}();
But this won't work as it will give you a syntax error. The reason you get a syntax error is as follows. When you create a function with a name (such as abc above), that name becomes a reference to a function expression, you can then execute the expression by putting () after the name e.g.: abc(). The act of declaring a function does not create an expression, the function declaration is infact a statement rather than an expression. Essentially, expression are executable and statements are not (as you may have guessed). So in order to execute an anonymous function you need to tell the parser that it is an expression rather than a statement. One way of doing this (not the only way, but it has become convention), is to wrap your anonymous function in a set of () and so you get your construct:
(function() {
//stuff
})();
An anonymous function which is immediately executed (you can see how the name of the construct is a little off since it's not really an anonymous function that executes itself but is rather an anonymous function that is executed straight away).
Ok, so why is all this useful, one reason is the fact that it lets you stop your code from polluting the global namespace. Because functions in javascript have their own scope any variable inside a function is not visible globally, so if we could somehow write all our code inside a function the global scope would be safe, well our self-executing anonymous function allows us to do just that. Let me borrow an example from John Resig's old book:
// Create a new anonymous function, to use as a wrapper
(function(){
// The variable that would, normally, be global
var msg = "Thanks for visiting!";
// Binding a new function to a global object
window.onunload = function(){
// Which uses the 'hidden' variable
alert( msg );
};
// Close off the anonymous function and execute it
})();
All our variables and functions are written within our self-executing anonymous function, our code is executed in the first place because it is inside a self-executing anonymous function. And due to the fact that javascript allows closures, i.e. essentially allows functions to access variables that are defined in an outer function, we can pretty much write whatever code we like inside the self-executing anonymous function and everything will still work as expected.
But wait there is still more :). This construct allows us to solve a problem that sometimes occurs when using closures in javascript. I will once again let John Resig explain, I quote:
Remember that closures allow you to reference variables that exist
within the parent function. However, it does not provide the value of
the variable at the time it is created; it provides the last value of
the variable within the parent function. The most common issue under
which you’ll see this occur is during a for loop. There is one
variable being used as the iterator (e.g., i). Inside of the for loop,
new functions are being created that utilize the closure to reference
the iterator again. The problem is that by the time the new closured
functions are called, they will reference the last value of the
iterator (i.e., the last position in an array), not the value that you
would expect. Listing 2-16 shows an example of using anonymous
functions to induce scope, to create an instance where expected
closure is possible.
// An element with an ID of main
var obj = document.getElementById("main");
// An array of items to bind to
var items = [ "click", "keypress" ];
// Iterate through each of the items
for ( var i = 0; i < items.length; i++ ) {
// Use a self-executed anonymous function to induce scope
(function(){
// Remember the value within this scope
var item = items[i];
// Bind a function to the element
obj[ "on" + item ] = function() {
// item refers to a parent variable that has been successfully
// scoped within the context of this for loop
alert( "Thanks for your " + item );
};
})();
}
Essentially what all of that means is this, people often write naive javascript code like this (this is the naive version of the loop from above):
for ( var i = 0; i < items.length; i++ ) {
var item = items[i];
// Bind a function to the elment
obj[ "on" + item ] = function() {
alert( "Thanks for your " + items[i] );
};
}
The functions we create within the loop are closures, but unfortunately they will lock in the last value of i from the enclosing scope (in this case it will probably be 2 which is gonna cause trouble). What we likely want is for each function we create within the loop to lock in the value of i at the time we create it. This is where our self-executing anonymous function comes in, here is a similar but perhaps easier to understand way of rewriting that loop:
for ( var i = 0; i < items.length; i++ ) {
(function(index){
obj[ "on" + item ] = function() {
alert( "Thanks for your " + items[index] );
};
})(i);
}
Because we invoke our anonymous function on every iteration, the parameter we pass in is locked in to the value it was at the time it was passed in, so all the functions we create within the loop will work as expected.
There you go, two good reasons to use the self-executing anonymous function construct and why it actually works in the first place.
It's used to define an anonymous function and then call it. I haven't tried but my best guess for why there are parens around the block is because JavaScript needs them to understand the function call.
It's useful if you want to define a one-off function in place and then immediately call it. The difference between using the anonymous function and just writing the code out is scope. All the variables in the anonymous function will go out of scope when the function's over with (unless the vars are told otherwise, of course). This can be used to keep the global or enclosing namespace clean, to use less memory long-term, or to get some "privacy".
It is an "anonymous self executing function" or "immediately-invoked-function-expression". Nice explanation from Ben Alman here.
I use the pattern when creating namespaces
var APP = {};
(function(context){
})(APP);
Such a construct is useful when you want to make a closure - a construct helps create a private "room" for variables inaccessible from outside. See more in this chapter of "JavaScript: the good parts" book:
http://books.google.com/books?id=PXa2bby0oQ0C&pg=PA37&lpg=PA37&dq=crockford+closure+called+immediately&source=bl&ots=HIlku8x4jL&sig=-T-T0jTmf7_p_6twzaCq5_5aj3A&hl=lv&ei=lSa5TaXeDMyRswa874nrAw&sa=X&oi=book_result&ct=result&resnum=1&ved=0CBUQ6AEwAA#v=onepage&q&f=false
In the example shown on top of page 38, you see that the variable "status" is hidden within a closure and cannot be accessed anyway else than calling the get_status() method.
I'm not sure if this question is answered already, so apologies if I'm just repeating stuff.
In JavaScript, only functions introduce new scope. By wrapping your code in an immediate function, all variables you define exist only in this or lower scope, but not in global scope.
So this is a good way to not pollute the global scope.
There should be only a few global variables. Remember that every global is a property of the window object, which already has a lot of properties by default. Introducing a new scope also avoids collisions with default properties of the window object.

In javascript functions, can you set this.function = function?

I have run into this jquery plugin and i quite understand how this works:
$.functionone = function(){
function setOptions(newOptions){
...
}
this.setOptions = setOptions;
}
What i dont understand is what does this actually do? this.setOptions = setOptions can you call a function without parenthesis? What is the relationship between this.setOptions and setOptions by itself?
Functions in JavaScript are objects like (nearly) everything else. When you do this:
this.setOptions = setOptions;
you're not calling the setOptions function, you're just assigning a reference to the function to a property, exactly like setting a property to any other object, like this:
var dt;
dt = new Date();
this.today = dt;
With functions, you'd do this so you can later call the function via the property (which sets up the this value to be the object the property's on, which is handy). It's a bit clearer what's going on if you use a different name for the property than for the function:
function functionName() { ... } // Declares the function
this.propertyName = functionName; // Sets the property
functionName(); // Calls the function (with `this` = the global object ["window", on browsers])
this.propertyName(); // Also calls the function (but with `this` = the object the property's on)
The pattern you identified, declaring a function and then separately setting a reference to it on an object, is frequently used to make sure the resulting function has a name. You can create a function and bind it to a property like this:
this.setOptions = function() {
...
};
...but then the function doesn't have a name (the property does, but not the function), which can be an issue when you're trying to debug because debuggers show you the names of functions in various contexts (call stacks, for instance). If a lot of your functions don't have names, even though the properties referring to them do, it makes debugging difficult. More about anonymous vs. named functions here. (There's also a difference in terms of when the function is instantiated, but going into it here would just complicate things.)
You'd think you could combine things, like this:
this.setOptions = function setOptions() { // <=== DON'T DO THIS
...
};
...but although that mostly works, it triggers a bug in Internet Explorer / JScript (it creates two different functions for that code, which is at best a memory waste and at worst a very subtle and time-wasting problem, as it was in this question).
The function setOptions is only called if you add parenthesis: setOptions(). If you do not add parenthesis, you have a reference to a function. This is just like a normal variable, only it contains a function reference instead of some other value.
If you set this.setOptions = setOptions, you make a function setOptions on the this object, which points to the same function as setOptions. That is, if you call it using this.setOptions(), the referenced function will be called.

Categories

Resources