Practical ASP.NET

JavaScript for an ASP.NET Developer: Constructing Functions

In the last two columns, I've been discussing my deepening understanding of JavaScript ("JavaScript for an ASP.NET Developer") and my appreciation of JavaScript's beauty as a language oriented around prototypes rather than objects ("JavaScript for an ASP.NET Developer: Learning to Function").

The last hurdle for me was attaching a constructor to a JavaScript "item." (I'm trying to stay away from using the word "object"; I think it does JavaScript a disservice to try and force it into an object-oriented mold).

One warning: Don't trust the code you see here until you get to the end of this column. For part of this column, the code I show you won't actually work.

Constructing a Function
In the object-oriented world, a constructor is a method, a named routine that you can call. In the JavaScript world, a close approximation is a function, referenced through a variable. This example defines a function and puts a reference to the function in the variable Customer:

var Customer = function()
{
 return true;
};

I can cause the function to execute by using the variable with the "invocation operator" (parentheses). This example calls the function that I just defined:

var result;
result = Customer();

Within a function, I can refer to it using the "this" keyword. I can also add a new element to the function just by naming the element and setting it equal to a value. This example, for instance, adds two elements to the function (named id and status) and sets them to string values:

var Customer = function()
 {
   this.id = "";
   this.status = "Active";
};

I could now write code like this. The second line sets the id element to a literal value and the third line retrieves the value of the status element:

var result;
Customer.id = "A123";
result = Customer.status;

A Functioning Constructor
Of course, the point of a constructor is to initialize internal variables like my id element. That's easy enough to do with a function: I just pass any initialization values as parameters to the function. For my Customer function, I first need to re-define the function to accept a parameter and then use it to set the value of the id element:

var Customer = function(customerId)
 {
   this.id = customerId;
   this.status = "Active";
};

I can now initialize the function's elements by calling the function like I would any other:

Customer("A123");

Using "this" and the ability to add new elements dynamically, I can also incorporate a function into my Customer function. This example adds a function that changes the status element and puts a reference to this "sub-function" in an element called markDelete:

var Customer = function(customerId)
 {
   this.id = customerId;
   this.status = "Active";
   this.markDelete = function()
   {
     this.status = "Deleted";
   }
};

Now I can invoke the function through its element using the invocation operator, as this code does:

Customer.markDelete();

The Truth and Using New
But I've been lying to you -- the code I've shown wouldn't give you the results that you might expect. To fully take advantage of what you've built, you need to use the JavaScript "new" keyword. Using the "new" keyword will not only run your constructor but will also use your function definition as a prototype to create a new copy. When you use the "new" keyword, you get back a new copy of your function, initialized by the code you put in the function.

So, to actually use the Customer function, I'd write code like this to initialize a new version of the prototype and store a reference to the result in a variable named cust:

var cust = new Customer("A123");

I could then use the cust variable to access the elements I added earlier:

var result;
cust.markDelete();
result = cust.status;

So how do you tell the difference between a variable holding a function that you can call and a function acting as a constructor that returns a new version of the prototype? The short answer is you can't. Both of these lines will compile, for instance, but only the first one will give you the results you expect -- a new copy of the prototype:

var cust = new Customer("A123");
var cust = Customer("A123");

The JavaScript community has, however, evolved a convention: Functions whose variables have names that begin with an uppercase letter (as my Customer variable does) should be used with the new keyword; functions whose variables have names beginning with a lowercase letter (as do the examples in my previous columns) can just be invoked directly.

It's not perfect but, you know, I can live with this. It's really a very cool language.

About the Author

Peter Vogel is a system architect and principal in PH&V Information Services. PH&V provides full-stack consulting from UX design through object modeling to database design. Peter tweets about his VSM columns with the hashtag #vogelarticles. His blog posts on user experience design can be found at http://blog.learningtree.com/tag/ui/.

comments powered by Disqus

Featured

  • Compare New GitHub Copilot Free Plan for Visual Studio/VS Code to Paid Plans

    The free plan restricts the number of completions, chat requests and access to AI models, being suitable for occasional users and small projects.

  • Diving Deep into .NET MAUI

    Ever since someone figured out that fiddling bits results in source code, developers have sought one codebase for all types of apps on all platforms, with Microsoft's latest attempt to further that effort being .NET MAUI.

  • Copilot AI Boosts Abound in New VS Code v1.96

    Microsoft improved on its new "Copilot Edit" functionality in the latest release of Visual Studio Code, v1.96, its open-source based code editor that has become the most popular in the world according to many surveys.

  • AdaBoost Regression Using C#

    Dr. James McCaffrey from Microsoft Research presents a complete end-to-end demonstration of the AdaBoost.R2 algorithm for regression problems (where the goal is to predict a single numeric value). The implementation follows the original source research paper closely, so you can use it as a guide for customization for specific scenarios.

  • Versioning and Documenting ASP.NET Core Services

    Building an API with ASP.NET Core is only half the job. If your API is going to live more than one release cycle, you're going to need to version it. If you have other people building clients for it, you're going to need to document it.

Subscribe on YouTube