{"id":277,"date":"2007-12-18T20:54:04","date_gmt":"2007-12-19T01:54:04","guid":{"rendered":"http:\/\/unitstep.net\/blog\/2007\/12\/18\/using-the-call-and-apply-methods-to-change-the-context-of-a-function-in-javascript\/"},"modified":"2007-12-18T20:54:19","modified_gmt":"2007-12-19T01:54:19","slug":"using-the-call-and-apply-methods-to-change-the-context-of-a-function-in-javascript","status":"publish","type":"post","link":"https:\/\/unitstep.net\/blog\/2007\/12\/18\/using-the-call-and-apply-methods-to-change-the-context-of-a-function-in-javascript\/","title":{"rendered":"Using the “call” and “apply” methods to change the context of a function in JavaScript"},"content":{"rendered":"

In JavaScript, the context that function is executing in is very important. What is context? Basically, the context of a function is what object it is “attached” to – this object will be the reference of the “this<\/code>” keyword within that function. Every function has a context -that is to say, every function is attached to an object. By default it is the window<\/code> object.<\/p>\n

You may have run into this particular aspect of JavaScript when working with event handlers. For example:<\/p>\n

function alertId()\r\n{\r\n  alert (this.id);\r\n}\r\n\r\ndocument.getElementById('someId').onclick = alertId;<\/code><\/pre>\n

This will return the “id” attribute of the element that the function has been attached to. You could attach the same function to multiple objects and each time you called it on a different object, it would return a different value, since the context is different. (Minor note: using element.attachEvent()<\/code>, as part of the Microsoft event handler model, does not change the context<\/a> of the function so “this<\/code>” will still refer to the window<\/code> object)<\/p>\n

However, there may be times when you want to change the meaning of this<\/code> without actually having to attach that a function to an object. Using the call()<\/code> and apply()<\/code> methods of the Function object can allow you to do this.<\/p>\n

<\/p>\n

Context is everything<\/h3>\n

Let’s backtrack for a moment. In JavaScript, many (but not all) variables are objects. This includes the references to all functions as well – they are also objects. In the example above, using “alertId<\/code>” (without<\/em> the parentheses) would refer to the Function<\/code> object that represents alertId<\/code>. As the Function<\/code> object is a predefined object in JavaScript, it has methods and properties associated<\/a> with it.<\/p>\n

Two of these methods are call()<\/code> and apply()<\/code>. Using these methods on a Function object allows you to set the context of that function – that is, what the “this<\/code>” keyword refers to. The two only in how arguments are passed to the function whose context is being redefined. For example apply()<\/code> takes an array of arguments like this:<\/p>\n

function someFunction(arg1, arg2)\r\n{\r\n  this.id = arg1 + arg2;\r\n}\r\n\r\nvar arrayOfArguments = ['valueOfArg1', 'valueOfArg2'];\r\n\r\nsomeFunction.apply(objectToBeUsedAsThis, arrayOfArguments);<\/code><\/pre>\n

The values in the second-argument array are then used as the arguments to the someFunction()<\/code> function. <\/p>\n

The call()<\/code> method is almost the same except it does not take an array of arguments, but rather just an indeterminate number of arguments that are all passed to the function. For example, the above could also be accomplished with this code:<\/p>\n

function someFunction(arg1, arg2)\r\n{\r\n  this.id = arg1 + arg2;\r\n}\r\n\r\nsomeFunction.call(objectToBeUsedAsThis, 'valueOfArg1', 'valueOfArg2');<\/code><\/pre>\n

I prefer to use apply()<\/code> sometimes since you can directly use the arguments<\/code><\/a> variable that is local within all functions. (The variable arguments<\/code> stores all the arguments that were passed to the function when it was called, and so this can be used in a situation with where it is desired to have a function with a variable number of arguments.)<\/p>\n

A useful example<\/h3>\n

So far, the examples posed have been fairly trivial. Let’s look at a real-world use of call()<\/code> to illustrate its usefulness. Remember the arguments<\/code><\/a> variable? Basically, you have access to this object variable whenever you’re inside a function since it stores all the arguments passed to this function. However, it’s not exactly an array (although it works like one sometimes) and thus it does not<\/em> have access to Array<\/code> methods such as join()<\/code><\/a>. <\/p>\n

We could easily convert it into an array by accessing each property by its index using a loop, but there’s an easier to way to do this. Consider the following code:<\/p>\n

function someFunction()\r\n{\r\n  var argsArray = Array.prototype.slice.call(arguments, 0);\r\n}<\/code><\/pre>\n

Using this one line, we have successfully converted the arguments<\/code> into a true Array object and stored the result in the argsArray<\/code> variable. How? First, we access the slice()<\/code><\/a> method on the Array<\/code> object through the prototype<\/code> property and then call()<\/code> the method telling it to use the arguments<\/code> object as this<\/code>.<\/p>\n

The slice()<\/code> method allows us to extract a section of an existing array. However, by using call()<\/code> we are able to apply its effects on the arguments<\/code> object that is similar to, but not exactly an Array<\/code> object. The second argument of ‘0’ merely indicates that we want to extract not just a part of arguments<\/code> but all of it. Since slice()<\/code> always returns an Array<\/code> object, we thus get back a true array containing the same data as the arguments<\/code> object. And that’s it!<\/p>\n

Note that the above example could be compacted even further. However, it looks very cryptic and can be confusing. (As if the previous example wasn’t confusing enough!) <\/p>\n

function someFunction()\r\n{\r\n  var argsArray = [].slice.call(arguments);\r\n}<\/code><\/pre>\n

This example works the same as the previous one. Instead of using Array.prototype<\/code>, we create a ‘dummy’ empty array to get access to the slice()<\/code> method. The second argument of ‘0’ isn’t needed, as if it is left out when using slice()<\/code> the entire contents will be returned.<\/p>\n

Contextual Conclusion<\/h3>\n

In short, using these methods to change the scope of a function can allow you to do some neat things with JavaScript that aren’t possible in some other languages. However, one should always be mindful to keep code readable and maintainable and to lessen the learning curve for those new to a language. <\/p>","protected":false},"excerpt":{"rendered":"

In JavaScript, the context that function is executing in is very important. What is context? Basically, the context of a function is what object it is “attached” to – this object will be the reference of the “this” keyword within that function. Every function has a context -that is to say, every function is attached […]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":[],"categories":[64,4,137],"tags":[],"_links":{"self":[{"href":"https:\/\/unitstep.net\/wp-json\/wp\/v2\/posts\/277"}],"collection":[{"href":"https:\/\/unitstep.net\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/unitstep.net\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/unitstep.net\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/unitstep.net\/wp-json\/wp\/v2\/comments?post=277"}],"version-history":[{"count":0,"href":"https:\/\/unitstep.net\/wp-json\/wp\/v2\/posts\/277\/revisions"}],"wp:attachment":[{"href":"https:\/\/unitstep.net\/wp-json\/wp\/v2\/media?parent=277"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/unitstep.net\/wp-json\/wp\/v2\/categories?post=277"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/unitstep.net\/wp-json\/wp\/v2\/tags?post=277"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}