Skip to content

Commit

Permalink
Accesor check
Browse files Browse the repository at this point in the history
- autobind skips accessors
- Fixes kodefox#5
  • Loading branch information
leykoss committed Feb 19, 2022
1 parent 1550845 commit 9a2c81b
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 0 deletions.
22 changes: 22 additions & 0 deletions src/__tests__/autobind-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
});
});
12 changes: 12 additions & 0 deletions src/autobind.js
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down

0 comments on commit 9a2c81b

Please sign in to comment.