Toolbox-XToolbox-X

Define Prototype Method

Safely defines methods on JavaScript prototypes (including built-ins) in an idempotent and non-enumerable manner.

definePrototypeMethod

Safely defines methods on JavaScript prototypes (including built-in prototypes like String.prototype, Array.prototype, etc.) in an idempotent manner. The defined method is non-enumerable by default and will not overwrite existing methods unless explicitly configured to do so.

Function Signature

function definePrototypeMethod<Proto extends object, Name extends keyof Proto>(
  proto: Proto,
  name: Name, 
  impl: (...args: unknown[]) => unknown,
  options?: ProtoMethodOptions
): void

Parameters

ParameterTypeDescription
protoProtoThe target prototype object (e.g. String.prototype).
nameNameThe method name to define on the prototype.
implFunctionThe function implementation of the method.
optionsProtoMethodOptions (optional)Property descriptor settings and overwrite options.

Example Usage

playground.ts

Behavior Details

Non-Enumerable by Default

By default, the defined method is marked non-enumerable (enumerable: false). This guarantees that it behaves exactly like native prototype methods and won't leak or appear during property iterations like for...in loops or Object.keys().


Types

ProtoMethodOptions

interface ProtoMethodOptions {
  overwrite?: boolean;     // Defaults to false. If true, overrides existing properties.
  enumerable?: boolean;    // Defaults to false. If true, makes property enumerable.
  configurable?: boolean;  // Defaults to false.
  writable?: boolean;      // Defaults to true.
}

Last updated: Sun, Jun 14, 2026 07:06:16AM (UTC)

On this page