Jump to content

help understanding this function


skaterdav85
 Share

Recommended Posts

Can someone help decipher this function?

function createBoundWrapper(obj, fn) {   return function () {	  return fn.apply(obj, Array.prototype.slice.call(arguments));   }}

I think I understand most of it. createBoundWrapper returns a function that, when executed, calls fn with obj as the supplied context for this and it passes an array as data. What I don't quite get is why it says Array.prototype.slice.call(arguments)Why not just Array.slice.call(arguments)?My guess is that I don't fully understand the prototype object. All I really know about it is that it is used to add methods and properties to all existing and future instances of an object.

Link to comment
Share on other sites

Array.prototype.slice.call(arguments) is similar to arguments.slice, but arguments.slice is undefined even though arguments is an array. So to call the slice method, it calls the array prototype method and runs it in the scope of the arguments array. It should also work if you leave out the prototype:

function createBoundWrapper(obj, fn) {   return function () {	  return fn.apply(obj, Array.slice.call(arguments));   }}function test(a, b){  alert(a + b + this.val);}var scope = {val: 10};var tmp = createBoundWrapper(scope, test);tmp(1, 2);var scope2 = {val: 20};var tmp2 = createBoundWrapper(scope2, test);tmp2(1, 2);

Link to comment
Share on other sites

thanks JSG. so does the prototype object inherit all the properties and methods of the object it is a part of, which is why you can call slice on prototype? I just looked up the arguments variable that comes with functions and apparently it is an object that has a few similarities as an array.http://www.seifi.org/javascript/javascript-arguments.html

Link to comment
Share on other sites

The prototype is basically the object definition, it contains all of the properties and methods that get added when you create a new object. So you can call any of those methods manually, but many of them expect this to point to an instantiated object of that type. So if you just call it manually, like manually calling Array.prototype.slice, you need to have it run in the scope of an array. That's what this does:Array.prototype.slice.call(arguments)That is calling Array.slice in the scope of arguments, so in the code for the slice method this will refer to arguments.

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

×
×
  • Create New...