/
index.js
38 lines (34 loc) · 928 Bytes
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
/*!
* smart-bind <https://github.com/tunnckoCore/smart-bind>
*
* Copyright (c) 2016 Charlike Mike Reagent <@tunnckoCore> (http://www.tunnckocore.tk)
* Released under the MIT license.
*/
'use strict'
var utils = require('./utils')
/**
* > Smart bind `ctx` to `fn` instead use of native `.bind`
*
* **Example**
*
* ```js
* var smartBind = require('smart-bind')
*
* function zoopark () { return this.foo }
*
* var bound = smartBind({foo: 'bar'}, zoopark)
*
* console.log(bound()) // => 'bar'
* console.log(bound.toString()) // => 'function zoopark () { return this.foo }'
* ```
*
* @param {Object|Function} `ctx`
* @param {Function} `fn`
* @return {Function}
* @api public
*/
module.exports = function smartBind (ctx, fn) {
fn = typeof ctx === 'function' ? ctx : fn
ctx = typeof ctx === 'function' ? null : ctx
return utils.isBound(fn) ? fn : utils.rename(fn, utils.getName(fn), ctx || this)
}