jackyalcine
jackyalcine

Reputation: 468

Simpler "Class" Definitions in JavaScript

I've noticed that in ECMAScript standards you have things like defineProperty, which is like defining properties and what not in a JavaScript object and prototype which extends the objects by use of methods and what-not. Is there a shorthand that could take you from:

Object.defineProperty(Person,"name",{
    type : "string",
    get : function(){ return this.$d.name; },
    set : function(_v){ this.$d.name = _v }
})

to something as simple as this:

function Person(args){
// ... snip ...

this.defineProperty("name",{
   get : function() { return $d.name },
   set : function(_v) { $d.name = _v; },
   type : "string"
});

// ... snip ...
}

I'm pretty sure that with the magic of JavaScript that there's a simpler way. But I might be just lazy. Any pointers?

NOTE: I'm avoiding the use of CoffeeScript, it's too much of a reminder of Ruby, IMHO.

Upvotes: 0

Views: 124

Answers (1)

Esailija
Esailija

Reputation: 140220

You can augment Object.prototype to achieve this:

Object.defineProperty( Object.prototype, "defineProperty", {
    value: function( name, pd ) {
        return Object.defineProperty( this, name, pd );
    },

    enumerable: false
});

Upvotes: 2

Related Questions