Sethen
Sethen

Reputation: 11348

Constructor and Method chaining with a superclass in JavaScript

I am having a little trouble with my code. I understand the concept of method chaining and constructor chaining but can't get it to work right. Here is what I have so far:

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

As you can see from the code above, nonNullSet is a subclass of Set and I am trying to augment the add method by checking for null or undefined values. If they exist, just continuing looping. If they are valid values, call the add method of the Set super class, rather than rewriting it.

To me, this looks right and I am not getting the results I want, so something isn't right. What am I doing wrong here?

Upvotes: 0

Views: 132

Answers (1)

ruakh
ruakh

Reputation: 183270

I see two problems:

  • continue skips to the next loop iteration, but the loop doesn't do anything anyway, so continue-ing inside it doesn't change anything. Instead, you should actually call Set.add inside your loop, giving it one element at a time — but only if the element is non-null.
  • console.log(nonNullSet.values) should be console.log(nonNull.values): nonNullSet is your constructor, nonNull is your instance.

Also, not exactly problems, but other things you should improve:

  • You should capitalize NonNullSet.
  • Inside Set.prototype.add, you should make i a local variable, by using the var keyword.
  • Your variable-names contain null, but instead of checking for nullity, you check for falsiness. (null is falsy, of course, but so are some other things.) I think this is a bit confusing.

Upvotes: 1

Related Questions