From 08fa50b9d4b0d336c90ea347400f79148b0d2d43 Mon Sep 17 00:00:00 2001 From: Steven Sojka Date: Fri, 19 May 2017 16:57:59 -0500 Subject: [PATCH] fix(bindAll): guard against getters that aren't functions --- src/bindAll.spec.ts | 18 ++++++++++++++++++ src/bindAll.ts | 17 +++++++++++------ 2 files changed, 29 insertions(+), 6 deletions(-) diff --git a/src/bindAll.spec.ts b/src/bindAll.spec.ts index e3cb2e7..9f35b0f 100644 --- a/src/bindAll.spec.ts +++ b/src/bindAll.spec.ts @@ -52,4 +52,22 @@ describe('bindAll', () => { myClass.fn2.call(null); expect(context).to.equal(null); }); + + it('should work with getters', () => { + @BindAll() + class MyClass { + get prop(): string { + return 'blorg'; + } + + fn() { + return this.prop; + } + } + + const myClass = new MyClass(); + + myClass.fn.call(null); + expect(myClass.fn()).to.equal('blorg'); + }); }); diff --git a/src/bindAll.ts b/src/bindAll.ts index 423d34d..42ca723 100644 --- a/src/bindAll.ts +++ b/src/bindAll.ts @@ -1,3 +1,4 @@ +import isFunction = require('lodash/isFunction'); import { copyMetadata } from './utils'; /** @@ -46,12 +47,16 @@ function bindAllMethods(target: Function, instance: any, methods: string[] = []) const descriptor = Object.getOwnPropertyDescriptor(proto, key); if (include && key !== 'constructor' && !instance.hasOwnProperty(key)) { - Object.defineProperty(instance, key, { - configurable: true, - enumerable: descriptor.enumerable, - value: copyMetadata(instance[key].bind(instance), instance[key]), - writable: descriptor.writable - }); + const value = instance[key]; + + if (isFunction(value)) { + Object.defineProperty(instance, key, { + configurable: true, + enumerable: descriptor.enumerable, + value: copyMetadata(value.bind(instance), value), + writable: descriptor.writable + }); + } } }