JavaScript for the C# Developer Part 7 – Prototypal Inheritance

Previous: JavaScript for the C# Developer Part 6 – Objects

In the previous post you learned that JavaScript has objects but not classes. The post demonstrates the use of a simple factory method to create a closure that contains an object’s private state and an object created via an object literal (http://jsfiddle.net/DougWare/3Z9M6/). I like this technique because it is simple, the way it works is clear, and it isn’t easy to screw up as is the case with constructor functions and the new keyword. However, it has a couple clear disadvantages:

  • There is no direct way to test the object to determine its origin
  • Every object produced by the factory has its own copy its methods and its use of memory is not optimal

For these reasons I only use object literals for occasions when there will only be a small number of instances of the object in question, ideally only one. This is usually the case, but a given system probably has a few objects of which many instances are created. For these objects a different approach is needed. Instead of creating these objects with literals I want to create them from named models that I can reuse and extend as needed. These models are called prototypes.

Class based inheritance versus prototypal inheritance

C# has classes. The structure of a given object instance is defined by its class. C# supports polymorphism via classes; one class inherits from another class and add to, or override, its parent’s definition. In C# all classes share a common ancestor, the Object class.

JavaScript does not have classes. Instead JavaScript objects serve the same role by acting as prototypes. New objects are created by copying existing objects. The existing object acts as a model that defines the new object. JavaScript supports polymorphism because you can modify the new object and use it as the basis of yet more objects. Instead of a class hierarchy, JavaScript has a prototype chain. At the top of the prototype chain is a common ancestor, a function named Object.

When you create an object literal you are inheriting from Object.

Every object but one has a prototype

The only object that doesn’t have a prototype is the top of the prototype chain, Object, just as Object in C# has no base class. The prototype of every object literal is Object. When you try to access a member of an object, JavaScript first checks the object for a member with the specified name. If it doesn’t find it, it checks the prototype, then the prototype’s prototype, and so on until it gets to the top of the prototype chain. If it isn’t found anywhere in the chain, it is undefined.

Confusing naming causes confusion

JavaScript functions have a property named prototype. The prototype property is not the function object instance’s actual prototype and it behaves differently in different browsers. Because of this, if you try to understand how prototypes work by focusing on this property, you may end up like this.


The best detailed explanation I have seen for all this is this article: Constructors considered mildly confusing. I am going to attempt to explain it without spending much time talking about what is going on under the covers and try to make things as simple as possible.

The key thing to remember is that the value of a function’s prototype property is not the function’s prototype – it is the object assigned as the prototype of objects created by the function when the function is a constructor. A function’s prototype property contains an object instance which is applied as the model to all object instances created by the function when the function is used as a constructor function via the new keyword.

Constructor Functions

To review, the previous post taught you that JavaScript includes the keyword new.
When JavaScript sees new in front of a function call the function is a constructor function. JavaScript creates a new empty object instance, executes the constructor, and returns a new object that contains the object as initialized by the constructor. All the constructor must do is use the this keyword to extend the new object instance with the desired properties and methods as follows (http://jsfiddle.net/DougWare/whx3L/).


This example illustrates that the redShirt object and the blueShirt object exist independently of each other and each maintains its own private state.

The problem with this example is that the constructor initializes the object’s members each time it is invoked. Every instance gets its own identical copy of the getColorSize function just as each would if I used an object literal returned by a factory method. This is where the prototype property’s object instance is beneficial.

An example of a constructor that takes advantage of a constructor’s prototype looks like this (http://jsfiddle.net/DougWare/QYpM6/).


In this example, the constructor, Animal, and the object, pig, have no members of their own. This is proven by using the hasOwnProperty function. hasOwnProperty tests to see if an object instance has a property that is part of the instance. If the property is part of the prototype chain, or if the property is undefined hasOwnProperty returns false. When the code invokes identify() it is invoking the function that is attached to the prototype because the instance does not contain a member named identify. The same is true of the name property, but when a new value is assigned to the instance’s name property, JavaScript adds the property to the instance and no longer needs to traverse the prototype chain (http://jsfiddle.net/DougWare/vGvfj/).


The prototype property is assignable and can be any object

In the examples above, Animal.prototype is extended one member at a time. However, because prototype contains an object instance, any object can be a prototype. Therefore, the example can be rewritten as follows (http://jsfiddle.net/DougWare/4DYGW/).


Extending the prototype, Extension methods

By now it should be clear that all instances created from the same constructor point to the same prototype instance. This is the reason that using prototype offers superior performance and memory usage when you have many instances of the same type of object. One implication of this is that changing or extending the prototype instance affects every object on the prototype chain (http://jsfiddle.net/DougWare/VE52D/).


An implication of this is that you can extend all of the built-in classes to add methods just as you can with extension methods in C#. JavaScript coerces the primitive types string and number to objects to allow access to their prototype objects. Douglas Crockford uses this technique to extend Object to create a simple object factory that works for any object instance (http://javascript.crockford.com/prototypal.html). You can see it in action in the next example (http://jsfiddle.net/DougWare/MJaXL/).


Multiple levels of inheritance

It is possible to have multiple levels of inheritance by applying the parent object’s prototype to the constructor function of the child object (http://jsfiddle.net/DougWare/nKYtW/).


I feel compelled to editorialize on this point. You should be suspicious of this sort of thing when you see it in a design. There are times when inheritance of this type is valuable, but in my experience this is uncommon. You should carefully weigh the complexity of this technique against the potential benefit of a simpler design.

Using instanceof and is isPrototypeOf to determine an object’s origin

There are times when you may need to test an object instance to determine its origin. Every object has a constructor property which is an object containing a prototype property. You can’t trust these values and you should not use them! Instead you can use the instanceof comparison operator to identify an object’s constructor. One of the benefits of instanceof is that you can test for any level of the prototype chain (http://jsfiddle.net/DougWare/RDQU2/).


The instanceof operator requires you to have a working reference to the constructor function for the right-hand side of the comparison. You may not have such a reference. As an alternative you can check to see if a given object is the prototype of another object with the isPrototypeOf method (http://jsfiddle.net/DougWare/fzSPm/).


In this example the constructor function is f(), but at the location of the test, f() is inaccessible and out of scope.

Conclusion

If you made it all the way through this post you probably get that using prototypes is much more complex than using object literals as described in the previous post. Limiting your use of this technique is a good idea if your code is to be used or maintained by developers who are likely to be confused by prototypes. If you only have one or two instances of a given object you definitely should not use this technique. If you will have many instances the performance and memory savings prototypal inheritance brings justifies the additional complexity.

This is the second to last post I currently have planned for this series. The final post will be about the very confusing this keyword. If you’ve made it this far, you should have no trouble understanding it!

Next: JavaScript for the C# Developer Part 8 – WTF is this?

Author: Doug Ware

Code Samples for Basic Client-Side Operations

Every once in a while I write a blog post to help myself find certain information later. This is one of those – even though I knew these articles existed, I had a hard time finding them the other day with Google and Bing.

SharePoint 2010 CSOM and JavaScript

SharePoint 2013 CSOM, JavaScript, and REST

Author: Doug Ware

 

Monkey Patched Hacking of SharePoint’s UI JavaScript

I need a little break from the JavaScript tutorials, so today I’m going to write something fun you can file under ‘necessity is the mother of invention’. Understand that what follows is not future proof and that it behaves differently in different versions of SharePoint. However, it is mostly the same between SharePoint 2010 and SharePoint 2013…

One of the holes in SharePoint’s JavaScript libraries is the lack of a direct ability to react to a user’s activities related to list items and forms. There are times when you may need to know that a user is viewing or manipulating items without resorting to server-side code. Fortunately, most of the time it is easy to hijack calls to the built-in JavaScript and insert code that does whatever you need. In one of my apps I use this technique to redirect to custom forms. This lets me leverage the stock list views but use custom list forms with no server-side footprint. Note that there are supported alternatives to this technique; you can specify custom forms for a content type via the server and client object models, but I had some special requirements that made those options less than desirable.

Init.js

SharePoint includes a file named init.js that contains a number of interesting functions that can be hijacked via a monkey patch. As you learned in JavaScript for the C# Developer Part 3 – Functions, JavaScript lets you treat functions just like any other type of variable. As a result you can change a function’s implementation by assigning a new function to the original function name. I explained this concept more fully in the post Monkey Patching and SharePoint / Office 365.

Here are the user interface elements and the useful functions they call that I have used this technique to intercept. Be advised that, unfortunately, there are some edge cases, like the infernal calendar view, that do things differently.

  • Edit Item ribbon button – STSNavigateWithCheckoutAlert
  • New Item ribbon button – NewItem2
  • Add link in list views – NewItem2
  • Item links in list views – EditLink2
  • Edit Properties ribbon button in document libraries and edit control block – EditItemWithCheckoutAlert
  • View Properties/View Item ribbon button and edit control block – EditItem2
  • Upload ribbon button in document libraries – EditItem2
  • Add Document link – NewItem2

Demo

Here is an example in a document library view in SharePoint 2013 Preview. I used a content editor web part to contain the following script (http://jsfiddle.net/DougWare/u83LV/).

When I select a document and click Edit Properties an alert displays before executing the original function.

If I view the properties the alert for EditItem2 displays.

 

Be careful with this technique. If you use it, be prepared to change when you upgrade to SharePoint 2016.

–Doug

Author: Doug Ware

JavaScript for the C# Developer Part 6 – Objects

Previous: JavaScript for the C# Developer Part 5 – Closures are Simple

In the posts on functions and closures the demonstrations illustrated procedural and functional programming techniques. JavaScript supports both of these styles, but JavaScript is an object oriented language. In fact unless a variable is undefined, null, boolean, string, or number it is an object. Functions, arrays, dates, and regular expressions are all objects and JavaScript even wraps the primitive types with objects for extensibility.

JavaScript is a classless language that supports inheritance through prototypes. The word prototype is a fancy way of saying ‘model’. Simply put, JavaScript lets you create new objects from existing objects instead of from classes. Prototypes will be covered in a future post. This one focuses on the basics of object creation and manipulation.

Collections of Name-Value Pairs

A JavaScript object is little more than a collection of name-value pairs. The name is a key and can be practically any string of characters. The value can be of any type including function. Values of type function are the only thing that distinguishes a method from a property. Unlike C#, JavaScript lacks property getters and setters. Many libraries, SharePoint’s CSOM included, follow a pattern that uses set_value() and get_value() methods to read and write protected values. However, this style is often a hallmark of a JavaScript library ported from another language, as is the case with CSOM, and is not necessarily a pattern you should follow.

You can access an object’s members by using dot notation (object.member) or square bracket notation (object[‘member’]). Since the size of scripts is generally a concern with web sites, the dot notation is preferred because it uses three less characters and most people find it more readable. One difference is that the bracket notation allows member names that are disallowed with dot notation. Another is that you can access members dynamically with square bracket notation as the following example shows (http://jsfiddle.net/DougWare/W6BcJ/).


In this example the object (remember that functions are objects) has a property named 2 + 2 == 4. Of course this would be a crazy thing to do in real life, but it shows how flexible JavaScript can be. This is in stark contrast to the amount of reflection code required to access a member via reflection in C# and it enables techniques seldom used in C# programs.

Creating Objects with Object Literals

The easiest way to create an object is with a literal expression with JavaScript Object Notation, JSON. In the JSON format the collection of name value pairs is wrapped in curly brackets, names are separated by a colon, and name value pairs are separated by a comma. If a name contains invalid characters, as in the example above, one need simply enclose the name in quotes. Here is an example (http://jsfiddle.net/DougWare/R5ufM/).


 
 

As you can see, JSON is very flexible! Since you can use any valid literal on the left side of the colon you can nest objects and include arrays (http://jsfiddle.net/DougWare/w5Ekn/).


 
 

This flexibility is a key reason so many people use JSON as a data interchange format preferred over XML.

The JSON Object

All of the popular modern browsers include a built-in object named JSON that includes two methods:

  • stringify() – Returns an object as a JSON formatted string
  • parse() – Returns an object from a JSON formatted string

It is worth noting that the JSON object ignores functions (http://jsfiddle.net/DougWare/7YWDg/).


Note that the alert contains an empty object for nestedObject instead of the doMath() function.

Constructor Functions

A function is a type of object. JavaScript includes the keyword new which creates a new empty object instance, executes the function as a constructor, and returns a new object that contains the object as initialized by the constructor. All the constructor must do is use the this keyword to extend the new object instance with the desired properties and methods as follows (http://jsfiddle.net/DougWare/whx3L/).


This example illustrates that the redShirt object and the blueShirt object exist independently of each other and each maintains its own private state.

This is my least favorite way to create objects – I really dislike how the new operator works because it simply changes the behavior of the function call and a call that accidently lacks new looks perfectly fine when you read it! This problem is easily seen in the following example (http://jsfiddle.net/DougWare/3VVzY/).


In this example the assignment to blueShirt is missing the new operator. The constructor function does not return a value and blueShirt is undefined, but the syntax is perfectly valid.

Another problem is that the value of this when new is missing is the window object. As a result, this.color and the other members of the object are attached to window and become global variables! (http://jsfiddle.net/DougWare/pkwrH/).


The behavior of this is one of the most confusing aspects of JavaScript and is the subject of a later post.

The Simple Object Factory Pattern

My personal preference is to use the object factory pattern and avoid the use of new. An object factory is a function that creates, initializes, and returns an object instance based on zero or more input parameters. There are a number of ways you can go about this in JavaScript and my way isn’t necessarily the best. Here are two alternative
approaches the latter of which being a full blown implementation of the pattern. I have no doubt someone will feel compelled to point out that what I’m showing here doesn’t fit the formal definition of the pattern.

My simple factory relies on a closure to give the instances private variables and an object literal to provide the scaffolding of the object. The object literal resembles a class. (http://jsfiddle.net/DougWare/3Z9M6/)


There is Another Way

…but I can’t explain it without first explaining prototypes which will be the topic of the next post, JavaScript for the C# Developer Part 7 – Prototypal Inheritance.

Until then, happy coding,
–Doug

Author: Doug Ware

JavaScript for the C# Developer Part 5 – Closures are Simple

Previous: JavaScript for the C# Developer Part 4 – JavaScript’s Dangerous and Wild Type System

One of the problems C# developers have wrapping their brains around JavaScript is that there are a few concepts that don’t clearly map to what they already understand; concepts with scary names. Closures are one of those concepts. Wikipedia has an article on closures that I think illustrates this point rather well – it takes a relatively simple topic and makes it sound really complicated! If you understood what it says on first reading you have my congratulations.

In JavaScript for the C# Developer Part 3 – Functions, I showed a number of ways you can use functions to protect your variables from collisions with other scripts. The first example I used looks like this.


This protects the variable x within the two functions, but it only allows for a simple sort of execution – I have to call foo whenever I want to invoke bar! Furthermore, what if I want to use bar in many different contexts and I want each of them to have a unique value for x? This is where closures come into play.

A Closure is a Cocoon of Love that Protects your Variables

A closure encapsulates (creates a protected wrapper around) the contents of a function allowing the contents to exist after the function executes. All that is required is for the function to assign its internals to something outside of itself or to return its internals via the return statement. Here is a simple example of a closure in action (http://jsfiddle.net/DougWare/t87kB/).


In this example the function foo() is executed twice. Each time the function bar() is returned and assigned to a variable: first f1 and then f2. Both calls create a closure that creates a protected copy of the variable i for the use of each closure. Executing f1() twice alerts the values 0 and 1. Executing f2() twice does the same thing proving that each has its own distinct copy of i.

The Key is the Call

The only aspect of this that I have seen confuse people after they understand the first example is that they sometimes think the closure is unique to individual functions. But this example shows that even though there are three functions within the outer function, there is only one closure (http://jsfiddle.net/DougWare/SwAdg/).


Now, you probably read that example and thought, ‘gee that’s obvious!’ Alright smarty-pants, try this one (http://jsfiddle.net/DougWare/wEZvq/)!


In this example, which uses jQuery, there are two buttons. Each if these is bound to a function that increments a variable named x. What will you see when you click one button and then the other?

The answer is 1 and then 2. The buttons share the same instance of x from the closure created by document ready – $(function(){}); is shorthand for $(document).ready(function(){});

If what we want is for each click function to get its own copy of x we could rewrite the sample as follows (http://jsfiddle.net/DougWare/wEZvq/2/).


In this version the function that is invoked for each of the buttons creates a closure. Click the buttons to see that each has its own copy of x.

Conclusion

Closures provide an effective way to protect you variables and manage scope. They offer encapsulation, but closures aren’t the only way to achieve encapsulation. You can use objects… which is the subject of the next post!

Next: JavaScript for the C# Developer Part 6 – Objects

–Doug

Author: Doug Ware

JavaScript for the C# Developer Part 4 – JavaScript’s Dangerous and Wild Type System

In the previous posts about variables and functions I wrote extensively about how to manage scope and protect your variables from colliding with other scripts. The ease with which you can accidently create or affect global variables is one way JavaScript is like a long sharp piece of metal to be handled with care. This is especially important given JavaScript’s beautiful type system.


Types of types

Whenever I write anything based on presentations I go back and re-research the things I say in the talk. I do this because I might have been wrong about something I said and I can’t deny anything I put down in writing. The original slide deck for this series has a slide titled Primitive Types. When I began outlining this post I went out and tried to find an authoritative source to confirm what that slide says only to discover several sources that showed my slide to be slightly wrong! The problem was that these sources disagreed with each other!

Here is an article from MSDN, one from the Mozilla Developer Network, and one from Wikipedia. Each describe the subject of JavaScript types a bit differently and if you do the same research I did you will find many others. Finally I fell back on the ECMAScript JavaScript Language Specification which says that the primitive types are:

  • Undefined
  • Null
  • Boolean
  • String
  • Number
  • Object

That list is very interesting because as you saw in the previous post the result of typeof() for a function is ‘function’ (even though a function is really an object):


Just as interestingly, the typeof(null) is ‘object’ (even though null is really a Null):


Both of these results are proper and correct according to the spec for typeof in ECMAScript JavaScript Language Specification!

It’s important to understand that there is no such thing as an official JavaScript implementation. Just as with HTML and CSS, there is a specification and many individual implementations from different vendors. Furthermore, some of these implementations are quite old and have interesting quirks that are preserved for backwards compatibility. I have read that the behavior of typeof with regards to null is a manifestation of this.

Therefore, it seems that if I try to apply rigor to my discussion of the type system I will go down the rabbit hole into wonderland and focus on minute details and that is not the goal of these posts! For the purpose of this discussion I’m going to be a little lazy and simply focus on the types as described by the possible return values of typeof.

  • undefined
  • object
  • boolean
  • number
  • string
  • object
  • function

Undefined

When you declare a variable in C# you specify its type either explicitly via the declaration or implicitly using the var keyword based on the return type of an expression. In JavaScript a variable’s type is determined by its value. Furthermore a JavaScript variable’s type can change by assigning a value of a different type. Consider the following example (http://jsfiddle.net/DougWare/KrDtv/).


The typeof statement returns a string value with the name of the type. JavaScript also includes the named constant
undefined of type
undefined whose value is undefined. This is illustrated by the following boolean expression (http://jsfiddle.net/DougWare/NAGAr/).


You can test for the value undefined in a function with arguments to determine if the caller supplied an argument (http://jsfiddle.net/DougWare/MXaWB/).


The test for undefined in this example is safe because the existence of a variable named arg within the function’s scope is certain. However, in cases where the existence of a variable with a given name is not guaranteed you should always use typeof (http://jsfiddle.net/DougWare/2D3ds/).


If you test an undeclared variable for any value including undefined a runtime error is the result!

Null

JavaScript provides a named constant
null of type
object whose value is null. Null means that a variable exists, but that its value is unknown. There is a very subtle difference between a variable whose value is unknown and a variable whose value is undefined, but the former acknowledges that there is a value that is unknown whereas the latter just says a value was not supplied. Improper use of null is one of the hallmarks of a C# developer who is hacking together some JavaScript code. It is possible to rewrite a previous example and test for the presence of an argument by testing for null (http://jsfiddle.net/DougWare/wZVLD/).


This code looks correct and it works as intended, but it has two things wrong with it. The first is that it implies arg has some unknown value. The second is that it relies on the second biggest mistake C# developers make when they write JavaScript (after the accidental creation of global variables) – reliance on type coercion.

The Perils of Type Coercion, == Versus ===

Unless you already understood the reason, you were probably wondering why the examples of undefined used === but the example of null used ==. The answer is that === evaluates both the value and the type and is called the identity operator, but ==, the equality operator, attempts to coerce the types before the comparison. Consider this example (http://jsfiddle.net/DougWare/NPre7/).


This example should make it pretty clear how dangerous it is to rely on implicit type coercion. Furthermore, the math example might give you different results depending on the particular JavaScript engine that executes the code. Because the * operator only does multiplication, the runtime coerces x to a number and returns 25. However, the + operator does addition as well as string concatenation and in this case the runtime coerces y to a string and returns 55.

Many of the ‘JavaScript WTF?!’ examples I have seen rely on some sort of type coercion to achieve crazy results, but many examples like the test for null are relatively benign. That said, I always look for and flag == when I review JavaScript code.

Coercion in Boolean Expressions

The uninitialized values of the primitive data types evaluate to false when coerced in a Boolean expression, but they don’t all evaluate to true in other cases. The number 1 coerces to true, but other numbers evaluate to false. Boolean expressions that contain null or undefined values always evaluate to false unless you are comparing to null or undefined. Consider this example (http://jsfiddle.net/DougWare/xrGjV/1/).


Pretty weird eh? The key takeaway is that you should not rely on type coercion in your boolean expressions because the rules are bizarre.

Every Rule has an Exception

The one scenario where I think it is generally OK to leverage type coercion is when you need to initialize an argument to a function that wasn’t supplied by the caller. This technique relies on the fact that undefined values in boolean expressions evaluate to false in conjunction with the boolean or operator, | (http://jsfiddle.net/DougWare/uY6MR/1/).


Explicit Casts

The previous example is still a bit lazy because it doesn’t validate that the argument is a valid type, but in my opinion it is perfectly correct to throw an error if you expect a named argument to be of one type but the caller provides a different type. However, there are still many situations where you might need to cast a value, especially when you need a number from HTML text like the value of an input field. The basic cast functions are:

  • Number()
  • String()
  • Boolean()

Perhaps unsurprisingly, these don’t behave quite the same way their implicit coercions do (http://jsfiddle.net/DougWare/7hHjd/).


This post completely ignored objects. I’ll talk about those soon, but that I’ll go back to functions and examine the scary sounding but simple concept of closures.

Next: JavaScript for the C# Developer Part 5 – Closures are Simple

–Doug

Author: Doug Ware

JavaScript for the C# Developer Part 3 – Functions

Next: JavaScript Types

In the previous post I wrote about the basic scoping rules in JavaScript. There is more to say on that subject but first you need to understand the basics of functions.

The way JavaScript uses functions is very different from the way C# uses functions. JavaScript is a multi-purpose language that allows a variety of programming styles: procedural, object-oriented, and functional. This is because functions are incredibly flexible. This is one of the reasons I compare JavaScript to a sharp piece of metal with no safety features and a reason some people dislike working with JavaScript (especially other people’s JavaScript). The flexibility of functions allows syntax that is very confusing when approached from a strictly object oriented language like C# where functions are generally encountered only as members of classes.

In this post I will ignore functions as they relate to objects and save that discussion for later. For now I’ll focus on functions as procedures and as variables. As an aside, one of the best blog posts I’ve ever read on any subject is Steve Yegge’s incredible Execution in the Kingdom of Nouns. It is written as a criticism of Java, but it applies to C# as well. If you feel like you must have classes in order to write good code, you might want to read that post before continuing to open your mind to the alternative style that JavaScript supports (but does not enforce as it also has objects) before continuing.

Functions can Contain Functions

In the previous post I showed several mistakes that cause implied or unintended global variables. Nested functions provide a mechanism to prevent this and protect variables from being stomped by other script. Consider the following example (http://jsfiddle.net/DougWare/85MgV/).


In this example we have two functions, foo() and foo2(), each of which contain a variable named x and a function named bar(). If you execute the code you will see that foo and foo2 do not interfere with each other and that they neatly encapsulate their contents.

Functions can be Anonymous

An anonymous function is a function that has no name. If you’ve used jQuery you have almost certainly created anonymous functions most commonly with $(document).ready().


In this example the highlighted portion is an anonymous function that is passed as an argument to the ready() function which executes it when the document is ready.

Functions are First Class Types

As you can see above, the anonymous function acts like a variable. That’s because it is a variable and its type is function. You can see this by evaluating an anonymous function with JavaScript’s typeof() function. (http://jsfiddle.net/DougWare/k7Bsq/)


I can rewrite the example with an actual variable to get the same result. (http://jsfiddle.net/DougWare/BCQrk/)


Function Statements and Function Expressions

The function keyword actually plays two roles. In the first example the function statement defined the functions foo() and foo2(). An expression is an operation that is evaluated at runtime and yields a result. In the examples where the function is assigned to a variable or passed as an argument function acts as an expression. The difference is very subtle but important because function statements are hoisted by the JavaScript runtime to the top of the call stack prior to execution, but expressions are evaluated during execution in place. This is illustrated in the following example. (http://jsfiddle.net/DougWare/XMbUL/)


When this script runs the alert Statement appears and then a runtime error occurs. If you just run this in JSFiddle the effect is that the second alert doesn’t display. If you use a debugger you will see the error.


nonHoistedExpression is undefined because the function expression is below the attempted use of the variable!

Immediately Executed Function Expressions

The first example in this post works but is inelegant when we consider a script which we want to execute but which contains variables which we want to protect (and we always want to protect our variables). Since functions are first class types, functions can be anonymous, and function is an expression, it is possible to combine these concepts to create an immediately executed function expression. Consider this simple example. (http://jsfiddle.net/DougWare/8eC3p/)


In this example the anonymous function is wrapped by parentheses and followed with another set of parentheses that contains the function’s arguments (if any).

This means that we can rewrite the first example as follows. (http://jsfiddle.net/DougWare/QELHB/)


Using an Immediately Executed Function Expression to Prevent Collisions

The previous example protects our code’s variables and functions from colliding with other code, but it is also commonly used to improve the safety of frameworks like jQuery. The jQuery library maps the variable $ to the jQuery() function to as shorthand. It does so to help keep scripts that use jQuery as small as possible. However, jQuery is by no means the only library that uses $ as shorthand ($ is a legal variable name). Therefore, jQuery includes the noConflict() function which stops this mapping to prevent collisions. However, using this by itself means your script files will be bigger because you have to spell out jQuery everywhere instead of using the shorter variable $.

Immediately executed function expressions are commonly used to prevent this conflict globally while preserving $ for scripts that desire as shorthand for jQuery. For example: (http://jsfiddle.net/DougWare/4CxQw/)


Hopefully at this point you understand how you can use functions to manage scope and prevent collisions caused by global variables. There is more to cover on functions, but before that I’ll return to variables in the next post and talk about data types.

–Doug

Author: Doug Ware
(I’m trying out Google’s verified author system)

 
 

   

Author: Doug Ware

New and Improved SharePoint Designer 2013 – Now with 100% less Designer!

It took a couple of weeks for people to really notice the most significant change in SharePoint Designer 2013 – the visual design views are removed. All that remains is code view!

As a developer this only affects me indirectly. However, I think it is a change that disenfranchises the hoard of power users who depend on this functionality to build solutions. There is a lively thread going on in the Microsoft forums: http://social.technet.microsoft.com/Forums/en-US/officeitpropreview/thread/8f8e2cb3-a90f-4653-9d22-050f9f0d8612. If you don’t like this change and would like to make your voice heard, that thread is the best place to give your feedback to Microsoft.

–Doug

Author: Doug Ware