is there a toSourceString() kind of function for Function in Javascript? - javascript

So, I'm looking for toSourceString() method for Function object which will return the source code of the Function object in String format.
For example, If I have
(function(a, b) {
function useThis(c,d) {
return 'hello' + c + d;
}
console.log(useThis('Jenny', 'Jim'));
}).bind(this);
kind of function, then I wish if I run toSourceString(), I will just get the inner source part of the function like:
function useThis(c,d) {
return 'hello' + c + d;
}
console.log(useThis('Jenny', 'Jim'));
Is there any default function that works across browsers? Or is there any Regex way to find some string and replace/remove the first and the end?

Try this:
myFunction.toString().replace(/^function[^{]+{/,'').slice(0,-1)
Gets the function, strips the beginning and end.

Related

a function (which requires parameters) as arguments of another function

I have been using functions as parameters. Now I need to pass a function A which requires parameters x generated by function B. I can do that too. by calling A in B with the parameters.
But my problem is, my function B accepts any kind of function, and it is not fixed. It may take function C also which requires parameter y or some function D that does not need any parameter.
Is this possible?
function B(done_function){
//some task generate some value
done_function();
}
function B(done_function){
//some task generate some value including args
done_function(args);
}
How can I make A, C and D functions execute with their arguments.
The top two examples won't work.
The normal way to handle this is to ignore it. Function B should simply not care about how other functions accept arguments. Instead it should only provide a standard and well documented interface to it's callback:
function B (done_function) {
// do some stuff to generate result
done_function(result);
}
Or if function B can possibly generate errors asynchronously then it should do done_function(err, result). Notice that all libraries do this. They don't care how you write your functions.
Now, how to pass various types of functions to B? Just wrap them around another function. For example, say you need to pass the result of B to a logger function and you need to pass a variable specifying the name of the file to log to. Just do this:
B(function(result) {
logToFile(debugLogFile, result);
});
Say for example you need to modify the result because the function you want to pass it to expect it to be in a specific format. Just do something like this:
B(function(result) {
var x = {
some_parameter: something,
result: result
};
doSomethingElse(x);
});
There is no scenario where function B needs to be aware of how you want to process the result it generates. It's you, the programmer, who is responsible to convert the result of function B appropriately before doing further processing.
You can make use of the functions call method:
function B(done_function){
//some task generate some value including args
done_function.call(done_function, args);
}
example jsfiddle
Let B call the callback with a single object as argument, which contains all information:
function B(done_function){
//some task generating some values, including args, for example:
var args = {
status: 3,
code: 'DEC',
location: 'Atlantic',
date: new Date('2017-01-01')
}
done_function(args);
}
Using ES6 destructuring in function parameters, you can filter out the information you need:
Function A could look like this:
function A({status}) {
console.log('status is ' + status);
}
B(A);
In the same way, C could look like this:
function C({code, date}) {
console.log('code is ' + code + ' on ' + date);
}
B(C);
Of course, ES6 destructuring is just a nice shortcut syntax, as you can do it also like this:
function A(response) {
console.log('status is ' + response.status);
}
B(A);
Alternative: use function's length property
If the distinction between different kinds of callbacks can be made on the basis of the number of parameters that are defined for them, then you could use the length property like this:
function B(done) {
var code = 'DEC';
var status = 1;
var location = 'Atlantic';
var date = new Date('2017-01-01');
switch (done.length) {
case 1:
done(status);
break;
case 2:
done(location, date);
break;
default:
done(code, status, location, date);
}
}
function A(status) {
console.log('status = ' + status);
}
function C(location, date) {
console.log('location = ' + location + ' on ' + date.toDateString());
}
B(A);
B(C);
Note the specific rules that apply for the length property's value.

Create a function that takes an object and a key as input - return value for key within the object

Just learning JS, came across this question on coursera. I can't even begin to answer this question; I'm not certain what it's asking. Sorry for the ignorance. Just looking for the basic format. I can write a function that takes input, but not certain how to do this. I've spent a while researching objects and it's not quite sinking in yet. Thanks!
You need to use multiple parameters. You need to separate the parameters with commas like:
function func(param1, param2) {
console.log("Parameter 1: " + param1);
console.log("Parameter 2: " + param2);
}
func(1, 2);
// Console:
// Parameter 1: 1
// Parameter 2: 2
In actual code this would look like the following:
function getValue(object, key) {
if (object.hasOwnProperty(key)) {
// Object.prototype.hasOwnProperty(key) returns if the specified object has the specified key in it
return object[key];
} else {
// The else statement is not really needed as the function already returned
// if the object has the specified key
return null;
// If you need this function for something specific, then you should return a default value
}
}
clean and clear:
function f(obj,keyname){
return obj[keyname];
}
Usage: f(myObj,my_key_field_name)
or simply obj[keyname] if you do not like to write a function

javascript function into variable

Happy Holidays to all.
I'm trying to execute a function that I have saved in a variable, as I could do this?
I tried this.
funcVar = 'function (a, b) {c = a + b; alert (c);}';
document.write (funcVar);
but has no functionality, I want to use that function that is in the variable at some point.
You need to:
Write it as a function, not a string
Call it, not write it to the document as if it were a string of HTML
Pass arguments as it doesn't make sense to add undefined to itself
You should:
Not use globals
Such:
var funcVar;
funcVar = function (a, b) {
var c = a + b;
alert (c);
};
funVar(1,2);
That's not a function, that's a string. You need to remove the quotes. And you need to execute it, not print it:
var funcVar = function (a, b) {c = a + b; alert (c);};
funcVar(23, 42);
This works. Thank you all.
var funcVar;
funcVar = 'function stop() {alert ("Test");}';
eval(funcVar);
stop();

Javascript function call like somefunction("Hi")("Hello")("How")

Please have a look at this code. I need to show a alert message "mikä on elämän tarkoitus?" using this code
window["mikä"]("on")("elämän")("tarkoitus")("?");
I need to write a function or piece of code that will show that alert message when I will execute that code.
I have written a function like this:
window["mikä"] = function(str){
alert(str);
}
which works when I call window"mikä" but if I add more like below in console I see a type error.
window["mikä"]("on")("Hello")("How");
My question is would it be valid way to call like below as there is multiple function signs?
window["mikä"]("on")("elämän")("tarkoitus")("?")
To achieve the functionality you are looking for one way is to write a function which returns a function which returns a function as the others mentioned. That works fine if the number of functions is known before hand. Another way is to use a functional programming technique called currying, which is
the technique of translating the evaluation of a function that takes multiple arguments (or a tuple of arguments) into evaluating a sequence of functions, each with a single argument (partial application).
You can write your own curry function like this:
function curry(func, args_) {
var self = this;
self.args = args_ || [];
return function() {
var extended_args = [].concat(self.args).concat(Array.slice(arguments));
if(extended_args.length >= func.length)
return func.apply(this, extended_args);
return new curry(func, extended_args);
};
}
var funcName = "mikä";
window[funcName] = curry(functionstr1, str2, str3, str4) {
alert(funcName + ' ' + str1 + ' ' + str2 + ' ' + str3 + str4);
});
window["mikä"]("on")("elämän")("tarkoitus")("?");
Here are some resources which can help you if you are interested in learning more about currying / functional programming in JS.
http://kukuruku.co/hub/javascript/an-interesting-task-for-an-interview-currying-and-partial-applicationof-a-function
http://tech.pro/tutorial/2011/functional-javascript-part-4-function-currying
Reginald Braithwaite's talk in NDC Oslo
You want the return value to be a function as well, so that additional calls on the return value will call the same function. Just add this
window["mikä"] = function(str){
alert(str);
return window["mikä"];
}
EDIT: Misread your question, this will make multiple alert messages. Sorry.
You probably want to nest the function calls
window["mikä"] = function(s1){
return function(s2) {
return function(s3) {
alert(s1 + ' ' + s2 + ' ' + s3);
}
}
}
window["mikä"]("on")("elämän")("tarkoitus")("?");
As for getting the function name inside the function, there's really no good way to do that, and it should be avoided.

Run a json string function

I have a json string like this:
json = "{'run': 'function() { console.log('running...'); }'}"
How do I run that function inside of the json string?
You're going to have to use the eval() (doc) function. A lot of people have a lot of feelings about this function. JSON is best for transporting data, not functions (see JSON). The functions ought to lay in the script on the page.
Also there's a syntax error in your posted code (function is wrapped in single quotes ('), and so is console.log's first parameter).
But...
json = "{\"run\":\"function() { console.log('running...'); }\"}"; //Fixed, thanks
obj = JSON.parse(json);
eval(obj.run); //Logs "running..."
Update:
Oh, and I was mistaken. Eval doesn't seem to like anonymous functions. With the revised code, it will parse json into an object with a run property that is a String, with value "function() { console.log('running...'); }". But when you eval(obj.run);, you will get a SyntaxError declaring an unexpected (. Presumably, this is the ( in function ().
So, I can think of two ways of dealing with this:
Remove the anonymous function in your actual JSON string (so, make your PHP forget about function () {), and eval it. This means it will be called as soon as you eval it.
What I think you want, is to be able to evaluate it to an anonymous function, that will be called when you want. So, you could write a wrapper function (you would need to follow option 1 for this as well):
function returnEval(str) {
return function () { eval(str); }
}
This would allow you to call it. So:
obj = JSON.parse(json);
obj.run = returnEval(obj.run);
obj.run(); //Logs "running..."
Hope this helps!
JSON is not really intended for that, but here seems to be a good example.
This works for me in Firefox:
var json = "{'run': 'function() { console.log(\\'running...\\'); }'}";
eval('var j = ' + json);
eval('var r = ' + j.run);
r();
Try this, it works:
var JS = { "function" : "alert( new Date().getTime() );" };
new Function ( "", JS["function"] )();
for nested functions you also can use something like this:
jQuery.each( JS, function( method, value ) {
new Function ( "a, b", "if ( a == 'function' ) { new Function ( '', b )(); }" )( method, value );
} );
I know that thread is old but i want to share with you guys. You can make string a json and parse it easily with these functions.
function makeString(val){
return JSON.stringify(val, function (key, value) {if (typeof value == 'function') {return value.toString();}return value;});
}
function parseIt(val){
return JSON.parse(string, function (key, value) {if (value.toString().search("function")>-1) {eval("var func = " + value);return func;}return value;});
}
Without using eval('function()') you could to create a new function using new Function(strName). The below code was tested using FF, Chrome, IE.
<html>
<body>
<button onclick="test()">Try it</button>
</body>
</html>
<script type="text/javascript">
function test() {
try {
var myJSONObject = {"success" : true, "jsFunc" : "myFunction()"};
var fnName = myJSONObject.jsFunc;
var fn = new Function(fnName);
fn();
} catch (err) {
console.log("error:"+err.message);
}
}
function myFunction() {
console.log('Executing myFunction()');
}
</script>

Categories

Resources