Webinar wrap-up: Julian on JavaScript II

ctodx
03 March 2011

On Monday, I continued my webinar series on learning JavaScript when you’re a C# developer. The topic this time was objects. You can watch the webinar here. The slidedeck is here.

Southern Guilford (NC) High School Street Signagephoto © 2010 Joe Wolf | more info (via: Wylio)Rather than just give you a file of the code I had and used during the webinar I thought I’d go over it here. First up was the extend function, designed to help with using and overriding a set of parameters or options.

var extend = function() {
  var obj,
      name,
      shift = Array.prototype.shift,
      target = shift.call(arguments);

  if (!target) { return {}; }
  obj = shift.call(arguments);
  while (obj) {
    for (name in obj) {
      target[name] = obj[name];
    }
    obj = shift.call(arguments);
  };
  return target;
};

The function is declared without any parameter list since we’re going to use the arguments array to get at them, and there may be several parameters passed in. In essence, extend(x, y) means “take x, modify it with the properties in y, and then return it.”

First, the function grabs the first parameter. (The shift function removes the first element in the array and returns it. We’ll be looking at call() next time.) If it’s falsy (null/undefined in this case), return an empty object. Now get the next parameter (again removing it), and using the for..in statement, copy the values (and their names) from that object to the target object. Keep doing this —removing a parameter, applying it —until there are no more. Finally return the object we’ve been extending.

In general, we call it like this:

var o = extend({}, { a: 12, b: 14, c: true }, { b: 42 });
console.log(o); // {a:12, b:42, c:true}

We start off with an empty object, extend with the next object parameter (so it would then be equal to {a:12, b:14, c:true}), and then extend it will the next one, to give the answer shown.

Here’s an example (that I fluffed in the webinar) showing how you could use it “in real life”.

var someProcess = function (options) {
  var defaultOptions = { color: "red", useRTL: false, position: { x: 0, y: 0 } };
  var config = extend({}, defaultOptions, options);

  console.log(config);
};

someProcess({ useRTL: true }); // {color:"red", useRTL:true, position:{x:0, y:0}}

(I made it a bit more interesting this time by having an object within my options object.) An easy exercise for the reader: modify extend so that you don’t pass in the target object at all, instead the function starts off by assuming an empty target object.

Onto the next bit of code: the Object.create method. Since it’s only available in ECMAScript 5 and JavaScript 1.6, here’s a simple way to define it no matter what.

Object.create = Object.create || function(obj) {
  var F = function() {};
  F.prototype = obj;
  return new F();
}

var interestingObject = {a:42, b:true, c:"hello"};
var o = Object.create(interestingObject);
console.log(o);

The function is declared as “use the real Object.Create if it exists, otherwise use this definition,” and then gives the replacement function. This function creates an object that inherits from (that is, has as prototype) some interesting object. Unless a property (or method) is overridden in the descendant object, its value will come from the prototype. We’ll go over this code in more detail next time, but in essence the method declares a function F, sets its prototype object to the passed-in object, and then constructs a new object by using F as a constructor. The new object inherits the passed-in object’s behavior and property values.

Finally, here’s the code for isArray. As mentioned in the webinar, it’s a fault in the language that there is no easy way to determine if an object is an actual array.

Array.isArray = Array.isArray || function(obj) {
  return Object.prototype.toString.call(obj) === "[object Array]";
};

Again a bit weird, but in essence we’re using the base object’s toString method on the object passed in. If we’d called toString in the normal way, the overridden method from the Array prototype would be used instead, which prints out the contents of the array.

Until next time, when we talk about functions, happy client-side coding!

Free DevExpress Products - Get Your Copy Today

The following free DevExpress product offers remain available. Should you have any questions about the free offers below, please submit a ticket via the DevExpress Support Center at your convenience. We'll be happy to follow-up.
No Comments

Please login or register to post comments.