Skip to content

Instantly share code, notes, and snippets.

@WebReflection
Last active December 15, 2015 23:38
Show Gist options
  • Select an option

  • Save WebReflection/5341317 to your computer and use it in GitHub Desktop.

Select an option

Save WebReflection/5341317 to your computer and use it in GitHub Desktop.
On JS interfaces and a possible `Object.prototype.implements()` method
Object.defineProperty(
Object.prototype,
'implements',
{
enumerable: false,
configurable: true,
writable: true,
value: function (target) {
return Object.getOwnPropertyNames(target).every(function(p){
var current = this,
aDescriptor = Object.getOwnPropertyDescriptor(target, p),
bDescriptor;
do {
bDescriptor = Object.getOwnPropertyDescriptor(current, p);
} while(!bDescriptor && (
current = Object.getPrototypeOf(current)
));
return bDescriptor != null && (
bDescriptor.value === aDescriptor.value &&
bDescriptor.get === aDescriptor.get &&
bDescriptor.set === aDescriptor.set
);
},this);
}
}
);
@WebReflection

Copy link
Copy Markdown
Author
var a = {
      toString: function () {}
    },
    b = {toString: a.toString};

alert(b.implements(a)); // true

b = {__proto__: a};
alert(b.implements(a)); // true

b = {whatever: a.toString};
alert(b.implements(a)); // false

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment