Last active
December 17, 2015 00:38
-
-
Save FireyFly/5522056 to your computer and use it in GitHub Desktop.
Get rid of `this` thing
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
"use strict" | |
// Attempt to shoehorn Lua's (or Python's) "first parameter is `this`" model | |
// into JS's object model. Makes us not have to worry about `this` at all. | |
Function.prototype.applyW = function (args) { | |
return this.apply(null, args) | |
} | |
function wrap(fn) { | |
return function (/*...*/) { | |
"use strict" | |
return this == null? fn.apply(null, arguments) | |
: /*else*/ fn.bind(null, this).apply(null, arguments) | |
} | |
} | |
//-- Testing area --------------------------------------------------- | |
var add = wrap(function (x, y) { return x + y }) | |
Number.prototype.add = add | |
console.log(add(1,2)) // --> 3 | |
console.log(add.call(1,2)) // --> 3 | |
console.log(add.bind(1)(2)) // --> 3 | |
console.log(add.applyW([1,2])) // --> 3 | |
console.log((1).add(2)) // --> 3 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment