原型函数中的Javascript子函数

时间:2017-04-13 14:15:36

标签: javascript function prototype

我需要扩展一个包含标题和正文的字符串编写器功能。在整个"字符串"之前,正文可以有多个附加行。被渲染。然后引用一个新对象。我的问题在于,当我调用原型的子函数时,身体无法通过总体功能访问。我不得不错过一些简单的......想法?感谢

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

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

不确定.Item函数的用途是什么?建议将名称调整为小写,其中属性不是函数,从this调用返回Item。或者,只需致电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());