I'm trying to abstract a JQuery's common behavior that allows me to compose code easier: encapsulate an object to when a set
-like method is called, it's executed and the object itself is returned (pretty like JQuery does).
Look:
let encapsulate = function (guy) {
return function () {
guy.call(this, [].slice.apply(arguments))
Object.setPrototypeOf(this, guy.prototype)
Object.getOwnPropertyNames(guy.prototype)
.filter(propName => propName.match(/set/g))
.forEach(propName => {
this[propName] = () => {
guy.prototype[propName].apply(this, [].slice.apply(arguments))
return this
}
})
}
}
A test case is:
// works
let date = new Date();
console.log(date.setDate(10)); // logs 1494447383428
console.log(date.getDate()); // logs 10
console.log(Date.prototype.setDate.apply(date, [20])); // logs 1494447383428
console.log(date.getDate()); // logs 20
// does not work
let ED = encapsulate(Date);
let date1 = new ED();
console.log(date1.setDate(10)); // should log date1 object but throws an error
Which throws an error Method Date.prototype.setDate called on incompatible receiver [object Object]
.
Could you help me? D: