efn

1.0.1 • Public • Published

Extracted Function (efn)

If you assign an object method to a variable (or pass it to a function as a callback argument) and then call it later, the method will be called without being bound to the object. In other words, it’ll have no this context. To fix this, use this module to “extract” the method from the object.

This module provides the same functionality as the proposed unary bind operator.

Installation

Requires Node.js 4.0.0 or above.

npm i efn

API

The module exports a single function.

Parameters

  1. obj (object): The object from which you want to extract a method.
  2. key (string, number, or symbol): The key that points to the function you’re extracting.

Return Value

The extracted function, bound to obj.

Example

class Test {
  a () { return this.b() }
  b () { return 'value' }
}
 
const test = new Test()
 
// Before:
 
test.a() // 'value'
 
const callback = test.a
callback() // Throws TypeError: Cannot read property 'b' of undefined
 
// After:
 
const efn = require('efn')
 
const extracted = efn(test, 'a')
extracted() // 'value'

Related

This module is part of the fn family of modules.

  • ffn: Filtering Function
  • jfn: Joined Function
  • mfn: Memoized Function
  • ofn: Overloaded Function
  • pfn: Possible Function
  • qfn: Qualified Function
  • vfn: Variadic Function
  • wfn: Wrapper Function
  • xfn: Extended Function
  • 3fn: Three-Way Comparison Function

Package Sidebar

Install

npm i efn

Weekly Downloads

0

Version

1.0.1

License

MIT

Unpacked Size

3.86 kB

Total Files

4

Last publish

Collaborators

  • lamansky