Just JavaScript - Function Object Self Reference |
Written by Ian Elliot | |||
Monday, 22 January 2018 | |||
Page 2 of 2
Function Self Reference – calleeThe arguments object is discussed in more detail in the next chapter but it has a callee property which is a reference to the currently executing function. This makes it very easy to write code the references properties of the function object without having to worry what the function is called. For example, if we write the previous function as:
then the function will work no matter what variable is used to access it. If you want to write functions that work with their own properties then it is a good idea to create a shortcut reference to arguments.callee:
Strict ModeThe one problem with using the callee property is that in strict mode this is not allowed and any attempt to use callee generates a runtime error. There are also moves to remove callee from a future version of JavaScript. Fortunately there is a better although slightly more complicated way of achieving the same result. Function Self Reference Pattern(Advanced)It is possible to add a self reference to a Function object but in its most convenient form it requires a constructor or factory function and the action of closure to create a private variable. All of these topics are covered in later chapters but the need to include a self reference within a Function object is so useful that it is worth presenting the technique here. The basic idea is to use a factory function which creates the Function object you want. There are two advantages of using a factory function. The first is that the Function object can be setup exactly as you want it before it is consumed and the second is that you can use closure to create a private variable. The only down side is that you have to think up a name for the factory function as well as a typical name for the function it produces:
You can use a Function statement if you want to. Next we create the Function object storing a reference to it in a local variable:
In this case the function simply returns the value of a property of the Function object. If we want to the object factory can also create the property and initialize it :
You can see that we can use self to reference the Function object when ever we need to. Finally the object factory has to return the Function object:
Putting all this together gives:
You can see the general principles:
To use the factory function all you do is:
Now when you call the function:
the execution of the code has no dependency on what you call the variable that references the function.
This is an extract from the book Just JavaScript by Ian Elliot. Buy Now: from your local AmazonJust JavaScript
|
|||
Last Updated ( Tuesday, 30 January 2018 ) |