Monday, May 14, 2012

JavaScript Object Class

JavaScript Object Oriented Framework

JavaScript is fairly quirky (you can learn it at the code academy). It is object oriented, but its a sort of duck typed version.

Every object is really an associative array, so writing foo.bar is the same as foo["bar"]. They are synonymous.

Curiously enough, JavaScript's object oriented framework has a base class called Object. Lets discuss its properties.

Object Properties

What properties does a generic object have?

1. It keeps track of its own constructor, for example:

var foo = new Array();
console.log(foo.constructor === Array); // prints "true"

The instanceof operator checks the value of the constructor property.

2. We can also convert an object to a string by a toString() method.

This does the obvious thing: returns a string representation of the object.

(Actually, if you're a mathematician, you might want to make a toTeX() method...)

3. What about converting an object to a primitive type (well, a primitive type except a string)? We have the valueOf() method.

4. Since we're duck typing objects, we might want to check the properties an object has. We can do this with the hasOwnProperty() method.

It's a function that takes a string, for example "toString", then checks to see if our object has it or not. If our beloved object has it, then foo.hasOwnProperty("toString") returns true.

5. The object base class has a method testing a given property if it's enumerable or not. In other words: it tests if we can use it in a loop construction. This method is called propertyIsEnumerable(). For example:

var foo = { bar:0 };
foo.propertyIsEnumerable("x"); // returns true
foo.propertyIsEnumerable("spam"); // returns false, since foo.spam is undefined
foo.propertyIsEnumerable("valueOf"); //returns false for inherited properties

6. The last method I'll discuss is kind of tricky. The isPrototypeOf() method is similar to the instanceof operator discussed above (see this discussion [StackExchange.com] for more details).

Object.prototype.instanceOf = function( iface )
{
    return iface.prototype.isPrototypeOf( this );
};

Addendum: to find all the properties of the Object class on YOUR system, run the following in your browser's javascript console (however you find that...on Mozilla, it's in the "Tools" part of the browser):

function getAllProperties(object){
    return Object.getOwnPropertyNames(object);
}
console.log(getAllProperties(Object));

/* prints out
[ 'prototype',
  'getPrototypeOf',
  'getOwnPropertyDescriptor',
  'keys',
  'defineProperty',
  'defineProperties',
  'create',
  'getOwnPropertyNames',
  'isExtensible',
  'preventExtensions',
  'freeze',
  'isFrozen',
  'seal',
  'isSealed',
  'length',
  'name',
  'arguments',
  'caller' ] */

No comments: