EloquentJavascript Ch.6"另一个Cell"部分构造函数中的奇怪行为

时间:2015-09-16 14:43:22

标签: javascript

我正在开发Eloquent Javascript第6章练习"另一个Cell"并发现了一些奇怪的东西。请查看我编写的构造函数的以下代码。 StretchCell继承自UnderlinedCell,也显示如下。

UnderlinedCell

function UnderlinedCell(inner) {
  this.inner = inner;
};
UnderlinedCell.prototype.minWidth = function() {
  return this.inner.minWidth();
};
UnderlinedCell.prototype.minHeight = function() {
  return this.inner.minHeight() + 1;
};
UnderlinedCell.prototype.draw = function(width, height) {
  return this.inner.draw(width, height - 1)
    .concat([repeat("-", width)]);
};

StretchCell构造函数版本1

function StretchCell(inner, minWidth, minHeight){
  this.inner = inner;
  if (minWidth > inner.minWidth)
    this.inner.minWidth = minWidth;
  if (minHeight > inner.minHeight)
    this.inner.minHeight = minHeight;
};

StretchCell构造函数版本2

function StretchCell(inner, minWidth, minHeight){
  this.inner = inner;
  this.inner.minWidth = Math.max(inner.minWidth, minWidth);
  this.inner.minHeight = Math.max(inner.minWidth, minHeight);
};

这两个版本的代码对我来说似乎都没问题,因为它们都是直接修改变量,并且两者都为它赋值,但是当我在eloquentjavascript网站上提供的沙箱中运行时,我从版本2获得错误。这很奇怪。我有什么东西可以在这里找到吗?

编辑: 错误我正在接收 -

TypeError: this.inner.minWidth is not a function (line 97 in function UnderlinedCell.minWidth) 
 called from line 12

1 个答案:

答案 0 :(得分:1)

 this.inner.minWidth = Math.max(inner.minWidth, minWidth);
 this.inner.minHeight = Math.max(inner.minWidth, minHeight);

在此代码之后,this.inner.minWidththis.inner.minHeight都成为Math.max()返回的值。在这种情况下,this.inner.minWidththis.inner.minHeight应该是函数,因此无法运行!