1

I encountered a strange error today.

When I invoked the below function in chrome, I got:

var t = function(i){console.log(i);console.log(eval("i"));};

t("123");

//the result in chrome

123

undefined

But the above code invoked in firefox, it came out just as I thought: the second log statement was the same as the first.

In my opinion,the eval statement will use the context of the anonymous function as its runtime context, which contains the parameters.

I didn't find any material involve eval context and parameter.

Can anyone tell me why ?


Actually,I used tempo.js to render html and came out a similar question as I listed above.

the source code is here:

    _replaceVariables: function (renderer, _tempo, i, str) {
        return str.replace(this.varRegex, function (match, variable, args) {
            try {
                ...

                if (variable === '.') {
                    val = eval('i');
                } else if (utils.typeOf(i) === 'array') {
                    val = eval('i' + variable);
                } else {
                    val = eval('i.' + variable);
                }
                .....
            } catch (err) {
                console.log(err);
            }

            return '';
        });
    },

When run in chrome,the eval statement got error like this:

TypeError: Cannot convert null to object

I can't figure out why this happened, so I tried the code at the beginning.

2
  • Looks like chrome eval function only execute code, not return value. Try eval("console.log(i)") in both chrome and firefox
    – Eugene
    Commented May 8, 2013 at 15:59
  • @Eugene it actually return value, it was my mistake. thx.
    – simplemx
    Commented May 8, 2013 at 16:39

1 Answer 1

1

The Chrome console implementation of the console functions involves some asynchronous behavior that causes weird issues like what you've discovered.

That said, in your particular case my Chrome logs "123" twice. I find it generally to be a really good idea to augment debugging output with some unique identifying text:

var t = function(i){console.log("param is " + i);console.log("eval result is " + eval("i"));};

The Chrome console output collapses repeated lines and prefixes them with a little circled counter:


(source: gutfullofbeer.net)

That little "2" before "123" means it was logged twice.

1
  • thank you for your great help, it's a mistake i made. i didn't notice the little "2":( .but I actually got a typeerror in an eval statement like that.do you know why?
    – simplemx
    Commented May 8, 2013 at 16:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.