Looking through the meteor TODOs app I noticed a particular class pattern.
class ListsCollection extends Mongo.Collection {
//Other methods, no constructor
}
export const Lists = new ListsCollection('lists');
This code uses new
, though there is no ListsCollection
constructor. My interpretation, is that the constructor of Mongo.Collection
is being called by prototype delegation.
Throughout the rest of my code, I am using Kyle Simpson's OLOO Pattern
and i would like to use the same pattern here.
const ListsCollection = {
init() {
//Call the constructor of Mongo.Collection
return this;
},
//Same methods
}
Object.setPrototypeOf(ListsCollection, Mongo.Collection);
export const Lists = Object.create(ListsCollection).init('lists');
I've started, however I am not sure how to call the constructor of the Mongo.Collection
class. Any suggestions would be appreciated :D.
EDIT - following answers
I have replaced the comment in my second code snippet with Mongo.Collection.call(this)
, which should have the desired effect. However, i get the error Error: use "new" to construct a Mongo.Collection
. I'm not sure the best way to work around this.
EDIT 2 - following investigation
The offending line found in the Mongo.Collection constructor function, causing the error is:
if (! (self instanceof Mongo.Collection))
throw new Error('use "new" to construct a Mongo.Collection');
since instanceof
tests for existence of Mongo.Collection.prototype
up the prototype chain, it is clearly not present.
This was solved by changing
Object.setPrototypeOf(ListsCollection, Mongo.Collection);
To
Object.setPrototypeOf(ListsCollection, Mongo.Collection.prototype);