DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones AWS Cloud
by AWS Developer Relations
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
AWS Cloud
by AWS Developer Relations
  1. DZone
  2. Coding
  3. Languages
  4. Bleeding edge JavaScript for object orientation

Bleeding edge JavaScript for object orientation

Giorgio Sironi user avatar by
Giorgio Sironi
·
May. 12, 11 · Interview
Like (0)
Save
Tweet
Share
5.29K Views

Join the DZone community and get the full member experience.

Join For Free

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);
    },
});
Object (computer science) JavaScript

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • Automated Testing With Jasmine Framework and Selenium
  • 5 Steps for Getting Started in Deep Learning
  • A Deep Dive Into AIOps and MLOps
  • Multi-Tenant Architecture for a SaaS Application on AWS

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: