Skip to content

Instantly share code, notes, and snippets.

@bbars
Last active August 15, 2018 19:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bbars/c2660981888e62707dd9e00fad7b4a9b to your computer and use it in GitHub Desktop.
Save bbars/c2660981888e62707dd9e00fad7b4a9b to your computer and use it in GitHub Desktop.
Example: Object.enableChaining(context2d) .setFillStyle('#333') .fillRect(0, 0, 30, 30) .rect(5, 5, 20, 20) .setFillStyle('#f90') .fill()
Object.enableChaining = function (obj) {
if (!obj || typeof obj !== 'object')
throw new TypeError("Argument obj is not an Object");
var names = {};
var protos = [];
var cur = obj;
var descr;
while (cur && protos.indexOf(cur) < 0) {
descr = Object.getOwnPropertyDescriptors(cur);
for (var k in descr) {
if (!names[k] && descr[k].configurable && (descr[k].writeable || descr[k].set || typeof obj[k] === 'function'))
names[k] = k;
}
protos.push(cur);
cur = cur.constructor && cur.constructor.prototype || null;
}
function definePropertySetter(name) {
var setterName = 'set' + name[0].toUpperCase() + name.slice(1);
if (typeof obj[setterName] !== 'undefined')
return;
Object.defineProperty(obj, setterName, {
configurable: true,
value: function (value) {
this[name] = value;
return this;
},
});
}
function wrapProcedure(name) {
if (typeof obj[name] !== 'function')
return;
var wrapperFunction = function () {
wrapperFunction._originalFunction.apply(this, Array.prototype.slice.call(arguments, 0));
return this;
};
wrapperFunction._originalFunction = obj[name];
Object.defineProperty(obj, name, {
configurable: true,
value: wrapperFunction,
});
}
for (var name in names) {
if (typeof obj[name] === 'function')
wrapProcedure(name);
else
definePropertySetter(name);
}
return obj;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment