diff --git a/src/__tests__/autobind-test.js b/src/__tests__/autobind-test.js index 82b0464..20367a5 100644 --- a/src/__tests__/autobind-test.js +++ b/src/__tests__/autobind-test.js @@ -50,4 +50,26 @@ describe('autobind', () => { expect(bar.getThis).toNotBe(Foo.prototype.getThis); expect(invoke(bar.getThis)).toBe(bar); }); + + it('should NOT bind class accessors', () => { + class Foo { + constructor() { + autobind(this, Foo.prototype); + } + + get getAccessor() { + throw 'Accesor called'; + } + + set setAccessor(val) { + this.value = val; + } + } + try { + let foo = new Foo(); + expect(foo).toNotBe(undefined); + } catch (e) { + expect(e).toBe(undefined); + } + }); }); diff --git a/src/autobind.js b/src/autobind.js index cc90613..4821f3e 100644 --- a/src/autobind.js +++ b/src/autobind.js @@ -21,12 +21,24 @@ function isFunction(item) { return (typeof item === 'function'); } +function isAccessor(proto: ?Object, name: String) { + let desc = Object.getOwnPropertyDescriptor(proto, name); + if (!!desc && (typeof desc.get === 'function' || typeof desc.set === 'function')) { + return true; + } + + return false; +} + export default function autobind(instance: Object, proto: ?Object) { if (proto == null) { proto = Object.getPrototypeOf(instance); } let propertyNames = Object.getOwnPropertyNames(proto); for (let name of propertyNames) { + if (isAccessor(proto, name)) { + continue; + } let value = proto[name]; if (isFunction(value) && !isExcluded(name)) { instance[name] = proto[name].bind(instance);