Javascript:Object.Create(原型)不起作用

时间:2016-09-29 22:43:46

标签: javascript

我在node.js中运行以下命令:

function TextCell(text) {
    this.text = text.split("\n");
}

TextCell.prototype.minWidth = function() {
   return this.text.reduce(function(width, line) {
      return Math.max(width, line.length);
   }, 0);
};

TextCell.prototype.minHeight = function() {
    return this.text.length;
};

TextCell.prototype.draw = function(width, height) {
    var result = [];
    for (var i = 0; i < height; i++) {
      var line = this.text[i] || "";
      result.push(line + repeat(" ", width - line.length));
    }
    return result;
};

function RTextCell(text) {
    TextCell.call(this, text);
}

RTextCell.prototype = Object.create(TextCell.prototype);

RTextCell.prototype.draw = function(width, height) {
    var result = [];
    for (var i = 0; i < height; i++) {
      var line = this.text[i] || "";
      result.push(repeat(" ", width - line.length) + line);
    }
    return result;
};

当我在console.log(RTextCell.prototype)时,我得到一个只有draw函数的原型。此外,当我记录(Object.create(Textcell.prototype))时,我得到了#34; TextCell {}&#34;。为什么看起来原型的克隆是空的?

编辑:我注意到了我的错误。在定义它之前,我创建了RTextCell类型的对象。这就是原型变空的原因。很抱歉不包括这部分

1 个答案:

答案 0 :(得分:1)

Why does it seem like the clone of the prototype is empty?

Because it has no own properties. Inherited properties don't show up in the console directly, but when you expand the object you can follow the prototype chain.