Last active
December 25, 2015 11:59
-
-
Save bloodyowl/6973181 to your computer and use it in GitHub Desktop.
Snippet: from an instance method to a static one.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
Sometimes in JavaScript you want a method to be | |
accessible in multiple contexts. | |
For instance as a static and instance method. | |
Here comes a little example. | |
*/ | |
var app = {} | |
Array.prototype.each = each | |
function each(fn, thisValue){ | |
var self = this | |
, i = -1, l = self.length | |
while(++i < l) { | |
if(fn.call(thisValue, self[i], i, self) === false) break | |
} | |
return self | |
} | |
Array.prototype.collect = collect | |
function collect(fn, thisValue){ | |
var self = this | |
, i = -1, l = self.length | |
, result = Array(l) | |
while(++i < l) { | |
result[i] = fn.call(thisValue, self[i], i, self) | |
} | |
return result | |
} | |
/* | |
You might want `each` and `map` to be | |
callable using `app.each(arr, fn, thisValue)` | |
and `app.map(arr, fn, thisValue)`. | |
The trick is actually quite simple. | |
*/ | |
var nativeCall = Function.prototype.call | |
;[ | |
"each" | |
, "map" | |
].each(function(key){ | |
var method = Array.prototype[key] | |
app[key] = function(){ | |
return nativeCall.apply(method, arguments) | |
} | |
}) | |
/* | |
What happens there is that nativeCall takes | |
an `[object Function]` as `thisValue`, and | |
its arguments are `thisValue` for the function | |
to call, and this function's arguments. | |
Using Function.prototype.apply on this method, | |
we define `nativeCall`'s `thisValue` as the function | |
we need. The function's `thisValue` is then our first | |
argument. | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment