I am using eval() to run a script from a string. Below is the code:
eval('console.log("hello")');
I will get hello from the console output. I wonder whether I can save the hello into an variable in the current context. So I am looking for something like this:
const output = eval('console.log("hello")'); // I expect the console output is returned from eval() function.
But I get an undefined response. Is there a way for me to do that?
It is impossible because console.log() only returns undefined, however you can make a function that will return something.
Example:
console.oldLog = console.log;
console.log = function(value)
{
console.oldLog(value);
return value;
};
const output = eval('console.log("hello")');
Hope this will help.
While the first answer works, it causes a "Maximum call stack size exceeded" error for my case.
Think this might be a better solution.
const originalLog = console.log;
console.log = function (...value) {
originalLog.apply(console, value);
return value;
};
const response = eval(code);
Have you try this?
out = ''
console.log = function(val){out = out + ' ' + val}
eval('console.log("test string")')
Related
<script>
var tarih = tarih();
alert(tarih);
function tarih() {
var s=emrah;
return(s);
}
</script>
Bu fonksion neden undefined dönüyor ?
Why "undefined" returns?
The reason it returns undefined, is because of the assigment
var s = emrah
is confusing JS. So, it looks for a var name emrah and doesn't find it. That is the reason, you get undefined. Plus, if you are looking at your console, it would already have given you an error message, that
emrah is not defined
You might want to try: (If that's what you wanted)
var s = 'emrah'
You are calling the method before its defined.
Change the code to something like this.
<script>
function tarih() {
var s='emrah';
return(s);
}
var tarih = tarih();
alert(tarih);
</script>
Well, i understand my question is a little bit strange and the answer seems obvious ("it's impossible !"), but, as JS is a very open language, i go on anyway :)
Let's say, we have the following code :
function dummy() {
}
var obj = new dummy();
var result = obj.aFunction('a','b');
Obviously, the JS interpretor says :
obj.aFunction is not a function
I understand his anger :) but is there a trick to bypass the interpretor (or something like that) or to create on-the-fly the aFunction function into the obj object before the interpretor evaluates all the stuff ?
I've red all about using dynamic function names and so on (using eval() and other tricks) but that don't solve my (weird) problem ...
Thanks in advance.
EDIT : Well, folks, thanks for your answers, but it's not my problematic.
In fact, i used to code in Java with AOP and what i want is :
Create a Valve (or something like this) that catches all the exceptions
Analyse the exception
if the exception corresponds to my 'no function' error, i create from scratch the function and execute it
I garbage this exception
if it's not the good exception i let it to continue its job
Unfortunatly, You cannot do that in JS. Using an ExceptionHandler is not sufficient because its API is too poor ...
But, Thanks to all ...
There are many ways to achieve this. Here is one:
function dummy() {
}
dummy.prototype.aFunction = function (a, b) {
alert(a + ', ' + b);
};
var obj = new dummy();
var result = obj.aFunction('a','b');
Here is a working example. Warning: it will pop up an alert box.
http://jsfiddle.net/X4F67/
Here is another, if you don't know the function name at runtime:
var name = 'aFunction';
function dummy() {
}
dummy.prototype[name] = function (a, b) {
alert(a + ', ' + b);
};
var obj = new dummy();
var result = obj[name]('a','b');
Fiddle: http://jsfiddle.net/X4F67/1/
Note that both of these affect the dummy prototype itself, so all instances of dummy would contain aFunction. If you instead want to work directly on the obj, you could use something like this:
...
var obj = new dummy();
obj[name] = function () { };
You can create a function on the fly, your code just has some issues.
First of all, setting:
var result = obj.aFunction('a','b');
Is making the browser think that obj.aFunction is an existing function that you are calling, you have to set the function.
obj.aFunction = function(a,b)
{
alert(a + ' ' + b);
}.bind(obj);
...then you could state:
var result = obj.aFunction;
If you were to say:
var result = obj.aFunction('a', 'b');
...after declaring obj.aFunction, it would be called at that line and alert right away.
Instead, you can do this:
window['result']('a', 'b');
As for declaring a function on the fly, such as writing out a function as a string and using eval() to evaluate the function and append it to a variable, I'm not sure why it doesnt work. This is what I tried:
obj.aFunction = eval("function(a,b){alert(a + ' ' + b);}.bind(obj)");
And I get:
Uncaught Syntax Error: Unexpected token (
Either way, hope that helps.
I have the code:
var here;
function setNews(data2){
here = data2;
console.log(here);//1st console log
}
console.log(here);//2nd console log
in the 1st console log the the data inside here are printed but in the 2nd console log it prints undefined how can i access the data inside the setNews function so that I can use it outside setNews.
Thank you.
Probably you need to review your architecture.
var here;
function setNews(data2){
here = data2;
console.log(here);//1st console log
}
//executed immediatly, `here` is not yet initialized by setNews
console.log(here);//2nd console log
Variable 'here' is being output to the console immedialy when javascript is loaded, but since it's undefined, console shows 'undefined'.
When later you call setNews('sample'), it will set global variable here but there is no point in that, because it was already outputted.
var here;
function setNews(data2){
here = data2;
console.log("inside function " +here);//1st console log
}
setNews("something");
console.log("outside function" +here);//2nd console log
Fiddle: http://jsfiddle.net/bmArj/
// initialize this to desired value.
var here = "your value";
I think...use return...
var here = setNews(2);
function setNews(data2){
here = data2;
console.log(here);//1st console log
return here;
}
console.log(here);//2nd console log
Please read this article on JavaScript Variable and Function Hoisting.
What happened is when you first declare the variable here, it wasn't initialized.
When you give here a value inside function setNews(), its value is not available to the outer console.log.
So you need to call setNews() first before displaying the content of here in the second call to the console, like so:
var here;
function setNews(data2){
here = data2;
console.log(here);//1st console log
}
setNews("some data here");
console.log(here);//2nd console log, it will display "some data here"
If you want to define a variable, (let's call it "here") that is automatically set to the value of some function named "setNews," then this might work better:
var here,
data2 = "the news!";
// Set value of "here" to processed data2
here = (function (news) {
// Process news
news = "This is " + news;
return news;
})(data2);
console.log(here);
// Prints "This is the news!"
I have something like this:
var test = {};
function blah() {
test[2] = 'filled';
}
blah(); // ! Hopefully confusion is now averted..
console.log(test);
//result test -> 2:"filled"
console.log(test[2]);
//result undefined
I don't understand why I'm getting 'undefined' in the second instance when according to the first instance, the property of that object clearly exists!
Does anyone have any ideas?
Thanks
OK, it seems that folk are getting confused as to what context the code exists in, for clarity sake I have now added the call to the blah(). but please refer to the comment under Jeff B's response!
Here is an example of relevant code so to say:
mydb = ..... //gets created here with relevant credentials
var test = {};
mydb.transaction(
function(transaction) {
transaction.executeSql("select * from mytable;", [], function(transaction,result) {
var r = result.rows.item(0);
test[2] = r.title;
}, errorHandler);
});
console.log(test);
//result test -> 2:"the title"
console.log(test[2]);
//result undefined
#Dancrumb
Your mention of the single-threadedness of Javascript gave me an idea, and I tried this:
window.setTimeout(function(){ alert(test[2]); },2000);
and it worked! I got the expected value to alert. Can you suggest how I can get around this without using a 'hack' like that above?
Because you aren't calling blah()?
Also, you want:
var test = [];
or:
var test = new Array();
EDIT
I ran the following code:
mydb = openDatabase('note','','Example',1024);
var test = {};
mydb.transaction(
function(transaction) {
transaction.executeSql("select * from mytable;", [], function(transaction,result) {
var r = result.rows.item(0);
test[2] = r.title;
}, errorHandler);
});
console.log(test);
console.log(test[2]);
in Safari 4.0.5
I got the following:
Object
No Properties
undefined
This is what I would expect to see. The object test does not have any properties assigned to it until the callback from mydb.transaction occurs and, since Javascript is single threaded, this cannot happen before the calls to console.log.
Since you're getting a different outcome, can you outline what browser and what version you are using?
This is pretty clearly an asynchronous issue. The simplest way of getting code to run after you set test[2], is to either put the code right there, or use another callback, and call it after you set test[2].
I am new to Javascript. I am trying to understand where "this" is bound to using different examples. I am using console.log to print some values as shown below.
function FuncObject(value) {
this.answer = value;
this.get_answer = function () {
return this.answer;
}
};
var f = new FuncObject(42);
var fanswer = f.get_answer;
console.log(fanswer())
console.log prints "function" instead of "undefined". document.writeln seems to print "undefined" which is the right one because this is bound to the window object which does not have answer. Now printing function confuses me. Now I am wondering what i should be using for logging. I am unable to find an explanation for this.
thanks mohan
Just incase you didn't notice, there's a typo in your posted code of
this.get_answer = funcition ()
With that in mind, I'm not entirely sure of your experience level so let me cover all the bases.
function FuncObject(value) {
this.answer = value;
this.get_answer = function () {
return this.answer;
}
};
var f = new FuncObject(42);
var fanswer = f.get_answer;
console.log(fanswer())
You're setting fanswer = f.get_answer where f.get_answer is a function, so as such it sets fanswer to the function equivalent of this.get_answer.
If you want the return value of f.get_answer you need to call f.get_answer(), which returns 42.
With what you put, console.log(fanswer()) does print undefined as expected.
If you simply do console.log(fanswer) it records it as function, also as expected.
I'm not sure why you would receive function as you stated in your question, because I definitely do not, jsbin.