2017-05-03 121 views
0

能否请您解释一下为什么这个代码:你能解释为什么“this”没有引用模板对象吗?

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')); 

返回:

undefined<p>Paragraph 2</p> 

预期的结果是:

<h1>Header</h1><p>Paragraph 2</p> 
+1

这根本不[这个'如何工作] (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this)。 'this'的值取决于如何调用周围的*函数,即'getTemplate'。 Object *文字*没有'this',只有函数。查看[对象字面声明中的自引用](http://stackoverflow.com/q/4616202/218196)以获取可能的解决方案。 –

回答

0

你可以尝试以下

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')); 
相关问题