2 Replies - 404 Views - Last Post: 06 May 2013 - 10:26 PM

#1 Dormilich  Icon User is offline

  • 痛覚残留
  • member icon

Reputation: 3481
  • View blog
  • Posts: 10,033
  • Joined: 08-June 10

A Question of Style

Posted 06 May 2013 - 02:02 PM

Hi there,

today my question is whether I should follow one or the other below described object creation strategies. I can see Pros & Cons for both strategies (case 1 has the cleaner prototype, case 2 does not have a separate constructor) and I can’t really decide, which is better.

case 1 - the explicit factory (not exactly a factory in the pattern sense, though)
// create a prototype object
var MyPrototype = {
    /* method definitions here */
};
// create the object itself
function MyPrototypeFactory(param) 
{
    var obj = Object.create(MyPrototype);
    Object.defineProperty(obj, "foo", {
        value: param,
        enumerable: true
    });
    return obj;
}
// instantiate
var foo = MyPrototypeFactory("bar");



case 2 - create the object from within the prototype
// create a prototype object
var MyPrototype = {
    /* method definitions here */
    create : function _create(param) {
        var obj = Object.create(MyPrototype);
        Object.defineProperty(obj, "foo", {
            value: param,
            enumerable: true
        });
        return obj;
    }
};
// instantiate
var foo = MyPrototype.create("bar");



So do you have any recommendations for me?

Dormi

This post has been edited by Dormilich: 06 May 2013 - 10:24 PM
Reason for edit:: bad idea removed


Is This A Good Question/Topic? 0
  • +

Replies To: A Question of Style

#2 andrewsw  Icon User is offline

  • Fire giant boob nipple gun!
  • member icon

Reputation: 3197
  • View blog
  • Posts: 10,703
  • Joined: 12-December 12

Re: A Question of Style

Posted 06 May 2013 - 05:11 PM

Version 2 seems a bit cyclical to me:

var foo = MyPrototype.create("bar");

var wibble = foo.create("wibble");  // odd?
alert(foo.foo);
alert(wibble.foo);

I don't think it should be possible to do this - unless it is intentional(?).

This post has been edited by andrewsw: 06 May 2013 - 05:11 PM

Was This Post Helpful? 0
  • +
  • -

#3 Dormilich  Icon User is offline

  • 痛覚残留
  • member icon

Reputation: 3481
  • View blog
  • Posts: 10,033
  • Joined: 08-June 10

Re: A Question of Style

Posted 06 May 2013 - 10:26 PM

OK, one more Con for case 2. although its not cyclical, you just have the ability to create new objects from an instance, kinda like a clone.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1