0xFADE
0xFADE

Reputation: 832

Combining javascript prototype styles

Is it possible to combine the following

function something() {}
function somethingElse() {}

somethingElse.prototype = new something();
somethingElse.prototype.someFunction = function() {}
...

with this

somethingElse.prototype = {
    someFunction: function() {},
    ...
}

and maintain the prototype-inheritance-chain

It is purely cosmetic I guess. I would just like to define all the functions inside {} rather then using a vast amount of ...prototype... = ...

I have seen quite a lot of either but never them brought together.

Upvotes: 1

Views: 509

Answers (4)

Shmiddty
Shmiddty

Reputation: 13967

You can use Object.defineProperties, but it's actually more verbose, and doesn't have support in legacy browsers:

Object.defineProperties(somethingElse.prototype,{
    someOtherFunction: {
        value:function() {...}
    },
    ...
});

Alternatively, you could add a rudimentary extend method to the Object prototype:

Object.prototype.extend = function(obj){
    for(var p in obj)this[p] = obj[p];
};

Which will allow you to do this:

somethingElse.prototype.extend({
    A:function(){'a'},
    B:function(){'b'}
});

I would generally recommend against this as modifying the prototypes of native objects can get dicey.

Upvotes: 0

Chris Tavares
Chris Tavares

Reputation: 30411

My personal favorite approach to this is to grab the underscore.js library. It's got a really nice method called extend to tack properties onto objects. So, I can do:

function something() {}
function somethingElse() {}

somethingElse.prototype = new something();

_.extend(somethingElse.prototype, {
    someFunction: function () { },
    someOtherFunction: function () { }
});

Upvotes: 1

Fabien
Fabien

Reputation: 13446

Well, they're quite the same indeed.

foo = {}
foo.bar = baz

is the same as

foo = {
    bar: baz
}

It's a matter of taste.

BTW : it is considered better style to name constructors (anything to be called with new) with a capital initial, to differentiate it from regular functions, because confusing them could do very bad things.

Upvotes: 0

bfavaretto
bfavaretto

Reputation: 71939

The difference is, in the second version, somethingElse instances will not inherit anything from something and its prototype chain. Considering your example code, that wouldn't make any difference, though.

Upvotes: 0

Related Questions