原型函数中的Javascript子函数

原型函数中的Javascript子函数,javascript,function,prototype,Javascript,Function,Prototype,我需要扩展一个包含标题和正文的字符串编写器函数。在渲染整个“字符串”之前,主体可以有多个附加行。然后引用一个新对象。我这里的问题是,当我调用原型的子函数时,主体无法访问总体函数。我必须错过一些简单的东西…想法?谢谢 不确定.Item功能的用途是什么?如果属性不是函数,建议将名称调整为小写,则从项调用返回此。或者,只需调用Primary.add()并省略.Item函数 var StringBuilder=function(){ 此标题为“”; 这个。body=“”; } StringBuild

我需要扩展一个包含标题和正文的字符串编写器函数。在渲染整个“字符串”之前,主体可以有多个附加行。然后引用一个新对象。我这里的问题是,当我调用原型的子函数时,主体无法访问总体函数。我必须错过一些简单的东西…想法?谢谢


不确定
.Item
功能的用途是什么?如果属性不是函数,建议将名称调整为小写,则从
调用返回
。或者,只需调用
Primary.add()
并省略
.Item
函数

var StringBuilder=function(){
此标题为“”;
这个。body=“”;
}
StringBuilder.prototype.Heading=函数(文本){
this.heading=text+'\n';
}
StringBuilder.prototype.Item=函数(){
还这个
}
StringBuilder.prototype.add=函数(字段,文本){
this.body+=''+field+':'+text+'\n';
}
StringBuilder.prototype.Append=函数(){
返回this.heading+'\n'+this.body;
}
var Primary=新的StringBuilder();
Primary.heading='My heading';
//var privalue=Primary.Item();//必要吗?
//Primary.add('bob','smith');
//Primary.add('sally','smith');
var privalue=Primary.Item();
privalue.add('bob','smith');
privalue.add('sally','smith');

log(Primary.Append())使用
新的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());

这是一个背景问题<代码>此
添加中
指的是
构造函数的新上下文。要使用
Primary
上下文调用add,您必须使用
call
bind
apply
从外部设置上下文。例如:
privalue.add.call(主要的'bob','smith')所以,这并没有完成我所寻找的。结果应该是我的标题,然后鲍勃:史密斯萨利:史密斯在下面。这仅显示正文中的单个项目,即最后一项。@JimGirard在
中使用
+=
运算符。设置
此.body时,使用add
函数来连接对
的调用。将
添加到现有字符串值,请参阅更新的帖子。
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());