0

When i try to fill some innerHTML with a method of an object I got an issue. Strangely, reffering to a function works. But this second way isnt convenient for what I would like to do, that is why I ask for help. Is there a way to make this work ?

There is some code to explain my problem :

<html>
<body>
    <div id = "content1"></div>
    <div id = "content2"></div>
    <script>
        var object1 = { 'render' : () => { return 'a'; } }
        var object2 = { 'render' : setContent() }
        function setContent() { return 'b'; }

        document.querySelector('#content1').innerHTML = object1.render; // Not working
        document.querySelector('#content2').innerHTML = object2.render; // Working
    </script>
</body>
</html>

And that is the render :

() => { return 'a'; }
b

Thanks a lot !!

Bap
  • 1
  • 1
    You should call the method, not just refer to it. The latter "works", because the value of `object2.render` is the value returned from `setContent`. – Teemu Feb 04 '20 at 20:16
  • Thanks a lot ! Crystal clear ! – Bap Feb 04 '20 at 20:29

1 Answers1

3

object1's render is the function signature, not the value returned from the function, which is why it looks "stringyfied" object2's render is the returned value from setContent()

If you want that anonymous function in there you can do it like so,

var object1 = { 'render' : (() => { return 'a'; })(); }
JDunken
  • 455
  • 2
  • 7