2017-04-13 88 views
1

我需要扩展一个字符串编写器函数,它包含标题和正文。在整个“字符串”被渲染之前,主体可以有多个附加行。然后引用一个新对象。我的问题在于,当我调用原型的子函数时,主体无法访问整体功能。我必须错过一些简单的想法。由于原型函数中的Javascript子函数

https://jsfiddle.net/hitman1733/n2od4s6s/

var StringBuilder = function() { 
    this.Heading; 
    this.Body; 
} 

StringBuilder.prototype.Heading = function(text){ 
    this.Heading = text + '\n'; 
} 

StringBuilder.prototype.Item = function() 
{ 
    this.add = function(field, text) { 
      this.Body = '  ' + field +': ' + text + '\n'; 
    } 
} 

StringBuilder.prototype.Append = function() { 
    return this.Heading + '\n' + this.Body; 
} 

var Primary = new StringBuilder(); 
Primary.Heading = 'My Heading'; 

var privalue = new Primary.Item(); 
privalue.add('bob', 'smith'); 
privalue.add('sally', 'smith'); 

console.log(Primary.Append()); 
+0

上下文问题。 'add'中的'this'是指'Item'构造函数的新上下文。要用'Primary'上下文调用add,你必须使用'call'或'bind'或'apply'来设置外部上下文。例如:'privalue.add.call(Primary,'bob','smith');' –

回答

0

不能肯定.Item功能的目的是什么?建议将名称调小写属性不是函数,从Item调用返回this。另外,只需拨打Primary.add()并省略.Item功能

var StringBuilder = function() { 
 
    this.heading = ""; 
 
    this.body = ""; 
 
} 
 

 
StringBuilder.prototype.Heading = function(text) { 
 
    this.heading = text + '\n'; 
 
} 
 

 
StringBuilder.prototype.Item = function() { 
 
    return this 
 
} 
 

 
StringBuilder.prototype.add = function(field, text) { 
 
    this.body += '  ' + field + ': ' + text + '\n'; 
 
    } 
 

 
StringBuilder.prototype.Append = function() { 
 
    return this.heading + '\n' + this.body; 
 
} 
 

 
var Primary = new StringBuilder(); 
 
Primary.heading = 'My Heading'; 
 

 
// var privalue = Primary.Item(); // necessary? 
 
// Primary.add('bob', 'smith'); 
 
// Primary.add('sally', 'smith'); 
 

 
var privalue = Primary.Item(); 
 
privalue.add('bob', 'smith'); 
 
privalue.add('sally', 'smith'); 
 

 
console.log(Primary.Append());

+0

所以,这并没有达到我要找的。这里的结果应该是我的标题,然后是鲍勃:史密斯莎莉:史密斯。这只显示了最后一个在身体中的单个项目。 –

+0

@JimGirard设置'this.body'将'.add'中的调用连接到现有的字符串值时,可以在'.add'函数中使用'+ ='运算符。 – guest271314

1

使用的new Primary.Item()是不完全正确的,我已经修改了这多一点的工作始终:

const StringBuilder = function() { 
    this.items = []; 
    this.heading = ""; 
    this.body = ""; 
} 

StringBuilder.prototype.heading = function(text) { 
    this.heading = text; 
} 

StringBuilder.prototype.body = function(text) { 
    this.body = text; 
} 

StringBuilder.prototype.addItem = function(field, text) { 
    this.items.push(`${field} : ${text}`); 
} 

StringBuilder.prototype.append = function() { 
    // note: using breaks only in the append method. 

    this.body += `\n${this.items.join('\n')}`; // join items to existing body. 

    return `${this.heading}\n${this.body}`; 
} 

const primary = new StringBuilder(); 

primary.heading = "My Heading"; 
primary.body = "My Body"; 
primary.addItem('bob', 'smith'); 
primary.addItem('sally', 'smith'); 

console.log(primary.append()); 

这里是JsFiddle