Scope in javascript
Posted by Mikef | Filed under MadeByPi™ Labs
I've seen quite a few different methods for retaining scope when calling a method in javascript. I mixed a few of my favourite methods up into one.
// first check that this method isnt already defined if (!Function.prototype.bind) { // extend 'Functions' prototype with a method called bind Function.prototype.bind = function(object) { // store a reference to 'this' var _this = this; // 'arguments' isnt truely an array, it's just very very similar. // If we call Arrays slice method on it without a start and end // parameter it'll return 'arguments' as an actual array. var args = Array.prototype.slice.call(arguments); // knock the first object from our args array. we'll know that it'll // always be 'object' and we already have a reference to that. args.shift(); // We want the 'bind' method to return a function that can be // executed at another time, so we'll return a function return function() { // this function will occasionally get called with additional parameters // such as event objects. so we'll convert the new arguments object into // an array.. var moreargs = Array.prototype.slice.call(arguments); // then join our other parameters onto the end var allargs = moreargs.concat(args); // if we have any arguments, we call 'apply' on the object, else we call 'call' return (allargs.length > 0)?_this.apply(object, allargs):_this.call(object); } } }
To use this, you call the 'bind' method on the function you wish to call and pass in the scope and then the parameters. Like this:
document.addEventListener("click", this.myFunction.bind(this, 1, 2, 3), false);
When you click on the document object, it'll call this.myFunction in the scope of 'this' (the current object), with the parameters 1, 2 and 3.







