构造函数和方法在JavaScript中使用超类进行链接

时间:2012-11-24 01:07:02

标签: javascript oop

我的代码有点麻烦。我理解方法链接和构造函数链接的概念,但无法使其正常工作。以下是我到目前为止的情况:

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的子类,我试图通过检查null或undefined值来扩充add方法。如果存在,只需继续循环。如果它们是有效值,则调用Set超类的add方法,而不是重写它。

对我来说,这看起来是正确的,我没有得到我想要的结果,所以有些事情是不对的。我在这里做错了什么?

1 个答案:

答案 0 :(得分:1)

我看到两个问题:

  • continue跳到下一个循环迭代,但是循环不会做任何事情,所以continue里面的东西不会改变任何东西。相反,你应该在循环中调用Set.add,一次给它一个元素 - 但前提是元素不是null
  • console.log(nonNullSet.values)应为console.log(nonNull.values)nonNullSet是您的构造函数,nonNull是您的实例。

此外,不完全是问题,但您应该改进其他事项:

  • 您应该将NonNullSet
  • 大写
  • Set.prototype.add内,您应该使用i关键字将var作为本地变量。
  • 您的变量名称包含null,但不检查是否为null,而是检查虚假。 (当然,null是假的,但其他一些东西也是假的。)我认为这有点令人困惑。