No, you can't, not unless it happens (which is unlikely) that cancel
closes over req
, req.user
, or req.user.hails
. (And even then, it would be a really dodgy thing to do.) If it doesn't there's no information provided to your method that you can use to remove the entry from the array.
You could add a method to hails
that both does the cancellation and removes the entry:
req.user.hails.cancelEntry = function(index) {
this[index].cancel();
this.splice(index, 1);
};
Yes, you can really add non-index properties to arrays like that. Note that they'll be enumerable, which is one reason not to use for-in
loops to loop through arrays. (More about looping arrays in this question and its answers.)
You could make it non-enumerable:
Object.defineProperty(req.user.hails, "cancelEntry", {
value: function(index) {
this[index].cancel();
this.splice(index, 1);
}
});
In ES2015+, you could even create a subclass of Array
that had cancelEntry
on its prototype...