0

Can you please explain why this code:

    function getTemplate(config) {

    var templates =  {

        template1: '<h1>Header</h1>',

        template2: this.template1+'<p>Paragraph 2</p>',

        template3: '<p>Paragraph 3</p>'
    }

    return templates[config];
}
console.log(getTemplate('template2'));

Returns:

undefined<p>Paragraph 2</p>

Expected result is:

<h1>Header</h1><p>Paragraph 2</p>
slash007
  • 23
  • 4
  • 1
    That's simply not [how `this` works](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this). The value of `this` depends on how the surrounding *function* is called, i.e. `getTemplate`. Object *literals* don't have a `this`, only functions do. Have a look at [Self-references in object literal declarations](http://stackoverflow.com/q/4616202/218196) for possible solutions. – Felix Kling May 03 '17 at 15:03

1 Answers1

0

You can try the following

function getTemplate(config) {
    var templates =  {
        template1: '<h1>Header</h1>',
        template2: function(){
            return this.template1+'<p>Paragraph 2</p>'
        }(),

        template3: '<p>Paragraph 3</p>'
    }
    return templates[config];
}

console.log(getTemplate('template2'));
NS0
  • 6,016
  • 1
  • 15
  • 14