Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Bleeding edge JavaScript for object orientation

DZone's Guide to

Bleeding edge JavaScript for object orientation

· Web Dev Zone
Free Resource

Start coding today to experience the powerful engine that drives data application’s development, brought to you in partnership with Qlik.

Although constructor functions are a conceptually useful method for defining classes in JavaScript, there is an alternative way to new for creating objects. This mechanism, defined in ECMA Script 5th edition, is still bleeding edge and under implementation by many browsers, but promises to eliminate classes altogether  (at least we won't see static classes anymore) favoring the direct creation of objects from a prototype.

The main function for manipulating objects in this way is Object.create(), which serves the purpose of instantiation. There are other functions available on Object in the new versions of JavaScript, which let you manipulate an object after instantiation, manipulating the scope of its properties and even adding getters and setters similar to PHP magic methods.

Advantages

With Object.create(), the prototype of an object can be set directly; thus you can define an inheritance chain, where each object refers to a parent object as prototype, without creating function constructors to use as classes, or anonymous functions to simulate the mechanism.

You can also set additional properties at the creation of objects, and these properties can be decorated with metadata such as enumerable, writable, and deletable; the metadata prevents the deletion or modification of a property, and tells the browser which properties should be listed with for..in.

Disadvantages

This class-free approach to object-orientation may be scary, but it's how JavaScript works. The instanceof operator will cease to work, as the created objects are instances of an anonymous class. I think the concept of class in JavaScript may be substituted in the future by Factory Methods which are not only responsible for calling the new operator (which now is wrapped by Object.create()), but also for deciding which properties and methods should tune an object.

This method is not well-supported for now, and fallback implementations as described in the Test-Driven JavaScript development book cannot totally emulate some things, like properties metadata or get/set interceptors.

Support

I told you this was bleeding edge! According to Mozilla,these are the browsers versions that support Object.create() in its full form, and with its companions:

  • Internet Explorer 9
  • Firefox 4
  • Chrome 5
  • No version of Opera.
  • Safari 5

The companions

JavaScript 1.8.5 (as Mozilla calls it) alias EcmaScript 5th edition (as the cross-browser specification says) is not only Object.create(): there are lots of other methods available on Object for ease of management. These are the most useful in my opinion, if you are well-versed with class-based programming languages;

  • Object.defineProperty(object, propertyName, descriptor) lets you add a property to an object after creation.
  • Object.seal(object) prevents other code from deleting or adding properties: attempts to do so will be ignored (without raising errors). Writable properties values can be changed.
  • Object.freeze(object) is the same as Object.seal() but also does not allow even the modification of existing properties.

Let's dive into some code

Here's a code sample, in the form of a test case for jsTestDriver, which exercises Object.create() and the other handy functions I cited earlier. You see we can manipulate objects and their prototype chains without defining a single class like in the classic inheritance examples.

TestCase("Object.create() and other useful functions from ECMAScript 5th edition", {
    "test should create a new object (prototype is null)" : function() {
        var o = Object.create(null);
        assertObject(o);
    },
    "test an invalid prototype throws a TypeError exception" : function() {
        try {
            Object.create(42);
            fail('No exception thrown.');
        } catch(e) {
            assertInstanceOf(TypeError, e);
        }
    },
    "test should create a new object with the given prototype" : function() {
        var proto = { property : 'value' };
        var o = Object.create(proto);
        assertEquals('value', o.property);
    },
    "test should allow setting properties" : function() {
        var o = Object.create(null, {
            property : {
                value : 42 // also Mozilla.org use always 42 in examples
            }
        });
        assertEquals(42, o.property);
    },
    "test should allow setting properties metadata" : function() {
        var o = Object.create(null, {
            property : {
                value : 42,
                writable : false
            }
        });
        o.property = 43; // no error! JavaScript always surprise me
        assertEquals(42, o.property);
     },
    "test it's not even an instance of Object" : function() {
        var o = Object.create(null);
        assertNotInstanceOf(Object, o); // the function constructor remains anonymous
    },
    "test Object.defineProperty() lets you define properties after construction" : function() {
        o = Object.create(null);
        Object.defineProperty(o, 'property', {
            value : 42
        });
        assertEquals(42, o.property);
    },
    "test Object.freeze() is similar to Object.seal(), but does not allow modification" : function() {
        o = Object.create(null, {
            property : {
                value : 42
            }
        });
        Object.freeze(o);
        o.property = 43;
        assertEquals(42, o.property);
        delete o.property;
        assertEquals(42, o.property);
    },
});

Create data driven applications in Qlik’s free and easy to use coding environment, brought to you in partnership with Qlik.

Topics:

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}