Tuesday, September 17, 2013

Javascript Function Constructors

BLUF: using Function constructors gives you greater control of the scope context and enables you to create dynamic functions but should be reserved for optimizations only as they are unintuitive to most developers and will rarely be worth it. 

In  reading Test Driven Javascript Development I discovered that you can create functions using the Function constructor.

This is in contrast to Function Declarations.

and Function expressions
So for an example, notice the Function below (log is just a supporting function)

  1. I had to pass log in by reference. We are used to this being added the the scope context automatically and in the case of Function that isn't the case.  
  2. The last string argument is the function body. 
  3. The first string argument contains multiple parameters separated by commas
  4. You can also pass in as separate arguments as shown by p4. 
I expect that this would rarely be used as it adds complexity and instead should be considered a tool for optimization because you have greater control over scope context / closure. 

It also could be used to dynamically build functions but IMO most of the time you will be able to achieve this with normal syntax and so this should be reserved for improving performance. 

No comments:

Post a Comment