UNPKG

es-toolkit

Version:

A state-of-the-art, high-performance JavaScript utility library with a small bundle size and strong type annotations.

54 lines (53 loc) 1.86 kB
const require_isArray = require("../predicate/isArray.js"); const require_isFunction = require("../../predicate/isFunction.js"); const require_toString = require("./toString.js"); const require_isObject = require("../predicate/isObject.js"); //#region src/compat/util/bindAll.ts /** * Binds methods of an object to the object itself, overwriting the existing method. * Method names may be specified as individual arguments or as arrays of method names. * * @template T - The type of the object. * @param object - The object to bind methods to. * @param [methodNames] - The method names to bind, specified individually or in arrays. * @returns Returns the object. * * @example * const view = { * 'label': 'docs', * 'click': function() { * console.log('clicked ' + this.label); * } * }; * * bindAll(view, ['click']); * jQuery(element).on('click', view.click); * // => Logs 'clicked docs' when clicked. * * @example * // Using individual method names * bindAll(view, 'click'); * // => Same as above */ function bindAll(object, ...methodNames) { if (object == null) return object; if (!require_isObject.isObject(object)) return object; if (require_isArray.isArray(object) && methodNames.length === 0) return object; const methods = []; for (let i = 0; i < methodNames.length; i++) { const name = methodNames[i]; if (require_isArray.isArray(name)) methods.push(...name); else if (name && typeof name === "object" && "length" in name) methods.push(...Array.from(name)); else methods.push(name); } if (methods.length === 0) return object; for (let i = 0; i < methods.length; i++) { const key = methods[i]; const stringKey = require_toString.toString(key); const func = object[stringKey]; if (require_isFunction.isFunction(func)) object[stringKey] = func.bind(object); } return object; } //#endregion exports.bindAll = bindAll;