JavaScript Extensions

Download code

I’ve created a few JavaScript functions that I find tend to come in handy when programming. I call them “extensions” because they extend the base window object with additional functions. I debated on namespacing these, but find that either they are used often enough that having to type a namespace every time becomes annoying, or the code is more readable without the namespace. Also, these are functions that are useful in their own right, outside of any library, so namespacing them to a library didn’t seem right to me. (If you are not familiar with namespacing in JavaScript don’t worry about it. I’ll discuss it in an upcoming post.)

Documentation is included in the source code, but below is a quick reference, so you can see what’s in there. All of these functions are added to the global window object, so you can use them directly. For example, to copy a JavaScript object, you can use:

1
2
3
4
5
6
7
8
source = {
  firstName: 'Jane',
  lastName: 'Doe',
  birthDate: new Date(2000, 10, 15)
};
 
// Use the copy function to create a duplicate of source
var dest = copy(source);

Or, to check if an object is an array, you can use one of the following methods:

1
2
3
4
5
6
7
var arr = [1,2,3];
 
if (isArray(arr))
  alert('It is an array!');
 
if (typeOf(arr) == 'array')
  alert('It is an array!');

This is only a first pass at these functions. In an upcoming post, I will be adding more extensions to this library. This will include adding some useful functions to the basic data types like String, Number, Date and Array. More to come, so stay tuned.


typeOf(obj)

Same as the built-in typeof operator, but distinguishes
arrays and dates from objects.

Params:
obj {object} The object to get the type of.
Returns:
{string} The name of the type of the object.


isUndefined(obj)

Checks if the object passed in is undefined.

Params:
obj {object} The object to be checked.
Returns:
True if obj is undefined, and false otherwise.


isNull(obj)

Checks if the object passed in is null.

Params:
obj {object} The object to be checked.
Returns:
True if obj is null, and false otherwise.


isString(obj)

Checks if the type of object passed in is a string.

Params:
obj {object} The object to be checked.
Returns:
True if obj is a string, and false otherwise.


isNumber(obj)

Checks if the type of object passed in is a number.

Params:
obj {object} The object to be checked.
Returns:
True if obj is a number, and false otherwise.


isBoolean(obj)

Checks if the type of object passed in is a boolean.

Params:
obj {object} The object to be checked.
Returns:
True if obj is a boolean, and false otherwise.


isDate(obj)

Checks if the type of object passed in is a date. This function will
distinguish between an object and a date.

Params:
obj {object} The object to be checked.
Returns:
True if obj is a date, and false otherwise.


isArray(obj)

Checks if the type of object passed in is an array. This function will
distinguish between an object and an array.

Params:
obj {object} The object to be checked.
Returns:
True if obj is an array, and false otherwise.


isObject(obj)

Checks if the type of object passed in is an object. This function will distinguish between an array and date vs. an object.

Params:
obj {object} The object to be checked.
Returns:
True if obj is an array, and false otherwise.


isFunction(obj)

Checks if the type of object passed in is a function.

Params:
obj {object} The object to be checked.
Returns:
True if obj is a function, and false otherwise.


copy(source, [dest])

Copies the properties of one object to another (including inner objects, arrays and non-prototype functions). Existing properties in the destination object are preserved, but will be overridden if those properties also exist in the source. Any functions in the prototype of the source will NOT be copied. If no destination object is passed in, a destination object will be created.

Params:
src {object} Source object that properties are to be copied from.
dest {object} Destination object that properties are to be copied to.
Returns:
The destination object.


scopedFn(scope, func)

Used to create a function pointer that will always be called against a specific object. Can be especially useful when assigning event handlers to DOM objects and you want the “this” variable to point to your own object rather than the DOM object.

Params:
{object} scope The object on which func is to be called.
func {function} The function to be called.
Returns:
A scope-corrected function that ensures func is always called against the given scope object.


emptyFn()

Shorthand for an empty function.

Tags:

Leave a Comment

Excellent JavaScript Basics Reference

For those of you who haven’t found this yet, Patrick Hunlock has an excellent JavaScript reference series, covering just about everything you could want to know about strings, numbers, arrays, dates and other JavaScript basics. It also includes some tutorials on AJAX and JSON. This is where I go when I need to look up some of JavaScript’s functions for the basic data types. It looks like his blog hasn’t been updated in almost a year now, but the information is still good.

I’ll be posting some JavaScript extensions soon. These are functions that will extend the basic JavaScript data types with custom functions, and add some useful global functions to the JavaScript tool set. Stay tuned.

Leave a Comment

Creating JavaScript Classes, Part 5: The Class Function (with screencast)

View Screencast | Download code

In the previous posts of this series, I looked at using JavaScript to create class hierarchies that would include property and method inheritance, and method overrides. Today, I’ve created a single JavaScript function that will automate this process for me. This is very similar in functionality to the YUI, ExtJS and other implementations that are out there, though this version is pretty bare-bones at this point. Which is good for learning the basics of how it all works.

Let’s first take a look at the original Employee class and see how I inherited from the Person class. The inline comments describe some of the more interesting points in the code, relating to inheritance, overrides and the like. Check out the earlier posts in this series to learn how these work.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
// The constructor function
function Employee(first, last, company) {
  // Bail out if inheriting
  if (arguments[0] === inheriting) return;
  // Call base constructor
  Employee.base.constructor.call(this, first, last);    
  this.company = company;
};
 
// Inherit prototype methods of Person
Employee.prototype = new Person(inheriting);
 
// Allows access to original base class methods
Employee.base = Person.prototype;
 
// New method added to this class
Employee.prototype.getWebSite = function() {
  return 'http://www.' + this.company + '.com';
};
 
// Overrides Person (and calls base class method)
Employee.prototype.getFullName = function(firstLastFormat) {
  if (firstLastFormat)
    return Employee.base.getFullName.call(this);
  else
    return this.lastName + ', ' + this.firstName;
};

Overall, this is a lot of code, and a lot to remember when creating classes and managing inheritance. Here is the same Employee class, using the new Class function.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
Employee = Class({
 
  // Inherits from person
  inherits: Person,
 
  // This is the constructor
  construct: function(first, last, company) {    
    // Calls base class constructor
    Employee.base.construct.call(this, first, last);
    this.company = company;
  },
 
  // New method added to this class
  getWebSite: function() {
    return 'http://www.' + this.company + '.com';
  },
 
  // Overrides method in Person (and calls base class method)
  getFullName: function(firstLastFormat) {
    if (firstLastFormat)
      return Employee.base.getFullName.call(this);
    else
        return this.lastName + ', ' + this.firstName;
    }
 
});

Now that’s a lot simpler to write, read and understand. Here is the function that makes the magic happen. I’ll be referring to this function a lot in the code explanations below.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
var inheriting = { };
 
function Class(init) {
 
  // Create function to be used as constructor that checks 
  // if we are inheriting, then call real constructor
  var cstr = function() {
    if (arguments[0] === inheriting) return;
    this.construct.apply(this, arguments);
  };
 
  // If we are inheriting, copy the prototype, 
  // otherwise assign a new prototype
  if (init.inherits) {
    cstr.prototype = new init.inherits(inheriting);
    cstr.base = init.inherits.prototype;
    delete init.inherits;    // Prevents adding to prototype later
  };
 
  // Copy all properties of init to the prototype 
  // (adds/overrides base class methods)
  for (var p in init)
    cstr.prototype[p] = init[p];
 
  // Return the constructor function (this is the class)
  return cstr;
 
};

As a side note, I rarely name a function as a noun unless it is intended to be used as a constructor function for creating objects, but in this case, I liked the look of the code to create a class. This, I think, is pretty clear as to what is happening.

Employee = Class({ /* ... */ });

Now, let’s break it down and look at how this Class function works.

Class is a function that takes a single argument. This argument is an initialization object, called init, and this argument describes the class that we will be creating.

Referring to the Class function code above, line 7 creates a new function called cstr (which stands for “constructor”). This function is the actual constructor for the new class that we are creating. This new function will ultimately be returned from the Class function, and it is the function that will be executed when creating a new instance of a class (in this case, Employee). Since this function is not actually executing yet, I’m not going to explain its contents just yet. We’ll get to that later.

On line 14, the Class function checks if the init argument has an inherits property. The init.inherits property is a reference to the class that this class inherits from (in this case, the Employee class inherits from the Person class). Lines 15 and 16 copy the prototype methods from the base class and create a reference to the original base class methods, respectively. These are equivalent to our previously manually coded lines (refer to the code at the top of this post for the original version of the Employee class):

1
2
3
4
5
6
7
8
9
// This...
cstr.prototype = new init.inherits(inheriting);
// ...is equivalent to this...
Employee.prototype = new Person(inheriting);
 
// And this...
cstr.base = init.inherits.prototype;
// ...is equivalent to this...
Employee.base = Person.prototype;

After the inheritance is completed, I delete the init.inherits property on line 17. I’ll explain why I’m doing this in a moment.

Lines 22 and 23 copy all of the methods of the init argument to the prototype of our new constructor function. We need to copy them one by one so that we don’t replace the inherited prototype methods. In this example, we inherited from Person, so the entire Person.prototype was copied to this constructor’s prototype in line 15. If we just assigned cstr.prototype = init, then we would replace all of the inherited prototype methods.

Now, back to line 17 where I deleted the init.inherits property. Deleting it prevents it from being copied to the prototype in lines 22 and 23.

Finally, in line 26, we return our new constructor function. This is our new class.

Now, back to the cstr function definition on line 7. This is the function I’ve returned from the Class function, and it represents the new class. So when I create a new class instance, this is the function that gets executed. The first line of this function (line 8 in the Class function code above) checks to see if we are inheriting by checking if the first argument is the unique inheriting object. If it is, then we don’t need to execute the entire constructor code (this was covered in Creating JavaScript Classes, Part 3 of this series). It is placed here so that I don’t have to worry about doing it myself, like I did in the original Employee class on line 4 (see first code listing at the top of this post).

The next line, line 9, executes the construct function that was defined in our init argument. Remember, this function is executing while creating a new class instance, so the this variable is set to the new, empty object that we are creating. The arguments variable contains a reference to any arguments that were passed into the constructor function, and we use the JavaScript apply function to pass those arguments to the construct function. Incidentally, I use the word “construct” (instead of “constructor”) for two reasons. First, some browsers were giving me problems with the name “constructor”, and second, “construct” is a verb which is how I generally name all my functions.

As a side note, I want to point out that the Class function takes a single argument, in JSON format. This means that a class definition could be loaded via an AJAX request from the server, and passed into the Class function. This is an advanced topic, but it would allow streaming classes from the server “on-demand”.

OK, that’s enough for today. Please let me know what you think!

Tags:

Comments (2)

Creating JavaScript Classes, Part 4: Method Overrides (with screencast)

View Screencast | Download code

This post is basically a summary of the screencast, which contains more details and explanations.

I’ve shown how to create inheritance in JavaScript, both for properties and methods. Now, I’m going to talk about method overrides. That is, I want to be able to replace a method of an ancestor class with a method of the same name from a descendant class, while still having access to the original method. JavaScript does not inherently allow for this, but we can make it work. I’m going to be building on my prior examples, so you might want to take a look at some of the previous posts in this series.

For reference, here is the class hierarchy again.

Figure 1 - Class Diagram

Figure 1 - Class Diagram

I’m going to override the getFullName method of the Person class, with a modified version in the Employee class. For reference, here is the Person class again. Incidentally, the use of the inheriting object was covered in the previous post on method inheritance.

1
2
3
4
5
6
7
8
9
10
11
var inheriting = { };
 
function Person(first, last) {
  if (arguments[0] === inheriting) return;
  this.firstName = first;
  this.lastName = last;
};
 
Person.prototype.getFullName = function() {
  return this.firstName + ' ' + this.lastName;
};

The Person class getFullName method returns the full name in the form “FirstName LastName”, but I want the Employee class to return it as “LastName, FirstName”. Straight overriding (i.e. replacing) of methods is easy in JavaScript. Just redefine the method in the descendant class.

1
2
3
4
5
6
7
8
9
10
11
12
function Employee(first, last, company) {
  if (arguments[0] === inheriting) return;
  Person.call(this, first, last);
  this.company = company;
};
 
Employee.prototype = new Person(inheriting);
 
// Overrides Person
Employee.prototype.getFullName = function() {
    return this.lastName + ', ' + this.firstName;
};

Line 10 is where I replace the getFullName method with the version for Employee. This does not, however, let me access the original version of the method from the base class, Person. In order to do that, I need to have a reference to the original method in the Person class.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
function Employee(first, last, company) {
  if (arguments[0] === inheriting) return;
  Person.call(this, first, last);
  this.company = company;
};
 
Employee.prototype = new Person(inheriting);
 
Employee.base = Person.prototype;
 
// Overrides Person
Employee.prototype.getFullName = function(firstLastFormat) {
  if (firstLastFormat)
    return Employee.base.getFullName.call(this);
  else
    return this.lastName + ', ' + this.firstName;
};

Line 9 adds the reference to the original Person.prototype methods. So now I can access them from Employee.base, as in line 14. Note that I have to use the JavaScript call function in order to have the base class method executed against my Employee instance (referenced by the this variable). If you are not familiar with the call method, I covered its use in Part 2 of this series.

Now when Employee.getFullName() is called, it checks to see if the firstLastFormat argument is true and, if it is, calls the base class (in this case Person) getFullName method.

This mechanism also works through multiple levels of the class hierarchy. For example, we could further override the getFullName method in the Manager class (which inherits from the Employee class).

1
2
3
4
5
6
7
8
9
10
11
12
13
14
function Manager(first, last, company) {
  Employee.call(this, first, last, company);
  this.workers = [];
};
 
Manager.prototype = new Employee(inheriting);
 
Manager.base = Employee.prototype;
 
// Overrides Employee
Manager.prototype.getFullName = function(firstLastFormat) {
  var name = Manager.base.getFullName.call(this, firstLastFormat)
  return name + ' (' + this.company + ')';
};

Note in line 8 that the Manager.base property references the Employee.prototype property. Therefore, line 12 calls the version of getFullName that is part of the Employee class. If firstLastFormat was passed with a value of true, then Employee.getFullName will call Person.getFullName. It all works, right through the class hierarchy.

In my next post, I think its about time to simplify all of this by creating a JavaScript object that will handle all this inheritance stuff for me. Yes, this will be very similar to what other libraries already provide. But it is so much more fun and educational to code it ourselves, isn’t it?

Tags:

Comments (1)

Creating JavaScript Classes, Part 3: Method Inheritance (with screencast)

View Screencast | Download code

For a complete explanation of the following code, watch the screencast. In the previous post, I looked at how JavaScript can access properties of ancestor classes in descendant classes. In this post, I am going to look at how to do the same with JavaScript functions. To keep things consistent, I’m going to build on the original class hierarchy that I used last week. For reference, here is that class hierarchy again:

Figure 1 - Class Diagram

Figure 1 - Class Diagram

If you recall from an earlier post, methods are added to constructor functions using the prototype object of that function. What I need to be able to do is have one class reference the prototype object of its parent class. This needs to work even if we have multiple levels of inheritance (as we do with our example classes).

Please note that I am not going to go into all the details of why these specific implementation techniques were chosen. View the screencast if you want to see all the details (you’ll also learn a lot more about method inheritance in the screencast).

In order to get the Employee class to inherit the methods of the Person class, I need to use a secret, special syntax that JavaScript understands. I call it secret because it doesn’t do what you think it does, and I call it special because it does something more useful than what you think it does.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
/**
 * @class Employee
 * @inherits Person
 */
function Employee(first, last, company) {
  this.company = company;
};
 
// The secret, special syntax of method inheritance
Employee.prototype = new Person();
 
Employee.prototype.getCompanyWebsite = function() {
  return 'http://www.' + this.company + '.com';
};

The secret, special syntax is in line 10 (in case you missed the comment right above it). Here’s the secret: it doesn’t really create a new instance of a Person object and assign it to the Employee.prototype property. Here’s the special: it does create a new instance of a Person object that has a reference to the methods of the Person.prototype object, and it will assign that same reference to Employee.prototype. This means that an instance of Employee (when we create one) will have access to all the methods of the Person class, because Employee.prototype references Person.prototype.

Now you might think that JavaScript is also smart enough not to execute the full constructor. After all, I’m not creating an object that I want to use. I’m just creating it so I can get a reference to the prototype. Well, JavaScript isn’t that smart. In this simple example, this is not a big deal. However, in a real application, where classes could be much larger, and constructors might do real work like alter the web page, this could be a bad thing. So I want to execute the constructor just enough to create a reference to the prototype, without actually executing any of the code within the constructor.

This is actually pretty simple to do. I can create a unique object, I’ll call it inheriting, and pass that object to the constructor function when I am setting up inheritance. Because this is a unique object, I can check for it in the constructor and, if it was passed in, bail before it actually executes any additional code.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
// Object used to signal that inheritance is being set 
// up, and that constructor code should not execute.
var inheriting = { };
 
/**
 * @class Person
 */
function Person(first, last) {
  // If first argument is the inheriting object, bail
  // out early, since we don't want to execute any code.
  if (arguments[0] === inheriting) return;
 
  // Constructor code when not setting up inheritance.
  this.firstName = first;
  this.lastName = last;
};
 
Person.prototype.getFullName = function() {
  return this.firstName + ' ' + this.lastName;
};

Line 3 is the unique inheriting object, and line 11 in the constructor checks for it. If it was passed in, which it only ever will be when inheritance is being set up, then the constructor is exited immediately without executing any additional code. If it wasn’t passed in, then execution proceeds as normal. I use arguments[0] as a convention, since some constructors will not expect any arguments (and therefore there will be no named arguments to reference).

The last thing I need to do is update the Employee class to utilize the inheriting object to signal the constructor function that inheritance is being set up.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
/**
 * @class Employee
 * @inherits Person
 */
function Employee(first, last, company) {
  this.company = company;
};
 
// The secret, special syntax of method inheritance
Employee.prototype = new Person(inheriting);
 
Employee.prototype.getCompanyWebsite = function() {
  return 'http://www.' + this.company + '.com';
};

On line 10 the inheriting object is now being passed to the Person constructor function during inheritance. Following this same logic, I can add the secret, special syntax to the Manager and Worker classes to have them inherit the methods of the Employee class. And because the Employee class already has a reference to the methods of the Person class, Manager and Worker will automatically inherit that reference as well. This gives inheritance through multiple class levels, and all is good.

In the next post, I’ll be looking at how to implement method overrides. That is, I want to be able to replace one method of a class with another method of the same name in the descendant class. But, I still want to be able to access the original method in the ancestor class when necessary. Although this is common in most object-oriented languages, its not a straight-forward thing to implement in JavaScript.

Tags:

Comments (1)