Skip to content
/ efn Public

[Node.js] Extracts a Function. Gets an object method while preserving its binding.

License

Notifications You must be signed in to change notification settings

lamansky/efn

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

6 Commits
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

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

About

[Node.js] Extracts a Function. Gets an object method while preserving its binding.

Resources

License

Stars

Watchers

Forks

Packages

No packages published