简体   繁体   中英

Javascript: Object.Create(prototype) is not working

I am running the following in 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;
};

When I console.log(RTextCell.prototype), I get a prototype with only the draw function. Also, when I log(Object.create(Textcell.prototype)) I just get "TextCell{}". Why does it seem like the clone of the prototype is empty?

EDIT: I noticed my mistake. I made objects of type RTextCell before defining it. That's why the prototype turned out empty. Sorry for not including that part here

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM