1

I want to know if it's possible to do something like this:

var myObject = { first: "Hello" + otherObject.second() + someVariable; }

Then call it and display in html: html += myObject.first() or myObject.first

I want it to display all values of "someVariable" and "otherObject.second()". Currently it display something like:

function () { return 2 * 2 }

but I want it to display "4" as a string/number so the result would be something like "Hello4". I hope you understand my question :) If thats not possible or it's a bad idea overall to do that, then let me know too and I will figure out something else.

2
  • I'm not sure I understand you're question but have you tried using the eval function? Commented May 9, 2015 at 13:42
  • Hey, no I did not try eval function, but i read about it before in lots of comments, and most peoples say that it should not be used. I tested it now and it seems to be what I am looking for. Commented May 9, 2015 at 13:53

2 Answers 2

1

Other people are right - you shouldn't use eval function. Especially, if it is possible to solve the problem without it.

In your case, you can replace this variable with a function, and call it when needed:

var myObject = {
    first: function() {
        return "Hello" + otherObject.second() + someVariable;
    }
}

Now, you can call it as a function:

alert(myObject.first());
// or
html += myObject.first();

otherObject.second() and someVariable will be calculated on function call.

Sign up to request clarification or add additional context in comments.

1 Comment

Hey, this is quite an old post, but your answer is correct so let me accept it :)
0

You can use:

console.log("foobar", myfn());

Comments

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.