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?