Just JavaScript - Function Object Self Reference
Written by Ian Elliot   
Monday, 22 January 2018
Article Index
Just JavaScript - Function Object Self Reference
Function Self Reference Pattern

JustJavaScriptSmall


Function Self Reference – callee

The 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:

function myFunction(a,b){
 var ans=a+b;
 return ans*arguments.callee.myConstant;
};
myFunction.myConstant=3.14159; alert(myFunction(1,0));

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:

function myFunction(a,b){
  var self=arguments.callee;
  var ans=a+b;
  return ans*self.myConstant;
};

Strict Mode

The 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:

var myFuncFactory = function () {

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:

var self = function () {
            return self.myValue;
           };

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 :

self.myValue=0;

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:

  return self;
};

Putting all this together gives:

var myFuncFactory = function () {
        var self = function () {
                     return self.myValue;
                   };
        self.myValue=0;
        return self;
      };

You can see the general principles:

  • use a factory function to return the Function object

  • set a local variable self to reference that Function object

  • use self within the function definition to reference any properties of the object

  • use self to create properties

 To use the factory function all you do is:

var myFunction=myFuncFactory();

Now when you call the function:

alert(myFunction());

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 Amazon

Just JavaScript 
An Idiomatic Approach

JustJavaScriptSmall

A Radical Look At JavaScript

 

Most books on JavaScript either compare it to the better known class based languages such as Java or C++ and even go on to show you how to make it look like the one of these.

Just JavaScript is an experiment in telling JavaScript's story "just as it is" without trying to apologise for its lack of class or some other feature. The broad features of the story are very clear but some of the small details may need working out along the way - hence the use of the term "experiment". Read on, but don't assume that you are just reading an account of Java, C++ or C# translated to JavaScript - you need to think about things in a new way. 

Just JavaScript is a radical look at the language without apologies.

Contents

  1. JavaScript – Essentially Different
  2. In The Beginning Was The Object
  3. Real World Objects 
  4. The Function Object
          Extract - The Function Object
          Extract - Function Object Self Reference
  5. The Object Expression
  6. Function Scope, Lifetime & Closure
    Extract Scope, Lifetime & Closure
    Extract Execution Context ***NEW!
  7. Parameters, Returns and Destructuring
         Extract - Parameters, and Destructuring
  8. How Functions Become Methods
  9. Object Construction
         Extract: - Object Factories
  10. The Prototype
         Extract - ES2015 Class and Extends
  11. Inheritance and Type
  12. The Search For Type
  13. Property Checking

Buy Now: from your local Amazon

Also by Ian Elliot 
JavaScript Async: Events, Callbacks, Promises and Async Await
Just jQuery: The Core UI 
Just jQuery: Events, Async & AJAX  

<ASIN:1871962579>

<ASIN:1871962560>

<ASIN:1871962501>

<ASIN:1871962528>

To be informed about new articles on I Programmer, sign up for our weekly newsletter, subscribe to the RSS feed and follow us on Twitter, Facebook or Linkedin.

espbook

 

Comments




or email your comment to: comments@i-programmer.info



Last Updated ( Tuesday, 30 January 2018 )