diff --git a/src/common/index.js b/src/common/index.js index fa2ed88..c67495d 100644 --- a/src/common/index.js +++ b/src/common/index.js @@ -6,4 +6,5 @@ export { getURLFileExtension } from './getURLFileExtension' export { isArray } from './isArray' export { isCorsSupported } from './isCorsSupported' export { isObject } from './isObject' +export { scope } from './scope' export { uuid } from './uuid' diff --git a/src/common/scope.js b/src/common/scope.js new file mode 100644 index 0000000..cb20fd6 --- /dev/null +++ b/src/common/scope.js @@ -0,0 +1,11 @@ +/** + * Bind methods on a given context + * + * @param {object} ctx Context + * @param {array} methodNames Method names + */ +export function scope (ctx, methodNames) { + for (let i = 0, l = methodNames.length; i < l; i++) { + ctx[methodNames[i]] = ctx[methodNames[i]].bind(ctx) + } +} diff --git a/test/common/scope.test.js b/test/common/scope.test.js new file mode 100644 index 0000000..30d6687 --- /dev/null +++ b/test/common/scope.test.js @@ -0,0 +1,28 @@ +import { scope } from '../../src/common' + +describe('common.scope()', () => { + it('Check if method is binded', () => { + const o = { + test () { return this } + } + + const testCall = o.test() + scope(o, ['test']) + + expect(testCall.hasOwnProperty('prototype')).toBeFalsy() + }) + + it('Check if methods are binded', () => { + const o = { + test1 () { return this }, + test2 () { return this } + } + + const test1Call = o.test1() + const test2Call = o.test2() + scope(o, ['test1', 'test2']) + + expect(test1Call.hasOwnProperty('prototype')).toBeFalsy() + expect(test2Call.hasOwnProperty('prototype')).toBeFalsy() + }) +})