Skip to content

Instantly share code, notes, and snippets.

@FireyFly
Last active December 17, 2015 00:38
Show Gist options
  • Save FireyFly/5522056 to your computer and use it in GitHub Desktop.
Save FireyFly/5522056 to your computer and use it in GitHub Desktop.
Get rid of `this` thing
"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