我的代码出了点小问题。我理解方法链接和构造函数链接的概念,但不能让它正常工作。这是我到目前为止所知道的:
function Set() {
this.values = [];
}
Set.prototype.add = function() {
for (i = 0; i < arguments.length; i++) {
this.values.push(arguments[i]);
}
}
var regSet = new Set();
regSet.add(10, 11, null);
console.log(regSet.values); // → [10, 11, null];
function NonNullSet() {
Set.apply(this, arguments);
}
NonNullSet.prototype = Object.create(Set.prototype);
NonNullSet.prototype.constructor = NonNullSet;
NonNullSet.prototype.add = function () {
for (var i = 0; i < arguments.length; i++) {
if (arguments[i] == null || arguments[i] == undefined) {
throw new Error("Can't add null or undefined");
}
}
return Set.prototype.add.apply(this, arguments);
}
var nonNull = new NonNullSet();
nonNull.add(10, 12, null);
console.log(nonNull.values); // → undefined
从上面的代码中可以看到,nonNullSet是Set的子类,我正在尝试通过检查空值或未定义的值来扩充add方法。如果它们存在,只需继续循环。如果它们是有效值,则调用Set超类的add方法,而不是重写它。
对我来说,这看起来是正确的,但我没有得到我想要的结果,所以有些事情是不正确的。我在这里做错了什么?
发布于 2012-11-24 09:15:02
我认为有两个问题:
continue
跳到下一个循环迭代,但是这个循环不做任何事情,所以它里面的continue
-ing不会改变任何事情。相反,实际上应该在循环中调用Set.add
,一次只给它一个元素--但前提是元素是non-null
.console.log(nonNullSet.values)
应该是console.log(nonNull.values)
:nonNullSet
是构造函数,nonNull
是实例。另外,不完全是问题,而是其他你应该改进的地方:
如果您应该大写NonNullSet
.
Set.prototype.add
i
var
null
来使名称成为局部变量,但是您不是检查空性,而是检查错误。(当然,null
是假的,但其他一些东西也是假的。)我认为这有点令人困惑。https://stackoverflow.com/questions/13537393
复制相似问题