OO style question

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Joe Kelsey

    OO style question

    When defining public methods, which style do you prefer:

    style 1:

    function myObject (...)
    {
    this.member = 0;
    }

    myObject.protot ype.method = function ()
    {
    //...
    }

    or style 2:

    function myObject (...)
    {
    this.member = 0;

    myObject.protot ype.method = function ()
    {
    //...
    }
    }

    Can I use this.prototype within an object definition?

    /Joe
  • Richard Cornford

    #2
    Re: OO style question

    "Joe Kelsey" <joe-gg@zircon.seatt le.wa.us> wrote in message
    news:151bebc0.0 308130842.39b0b 942@posting.goo gle.com...[color=blue]
    >When defining public methods, which style do you prefer:
    >
    >style 1:
    >
    >function myObject (...)
    >{
    > this.member = 0;
    >}
    >
    >myObject.proto type.method = function ()
    >{
    > //...
    >}
    >
    >or style 2:
    >
    >function myObject (...)
    >{
    > this.member = 0;
    >
    > myObject.protot ype.method = function ()
    > {
    > //...
    > }
    >}
    >
    > Can I use this.prototype within an object definition?[/color]

    You can, but you probably should not assign function expressions to a
    constructor's prototype from within the constructor. Each inner function
    expression within a constructor will represent a new function object [1]
    so with each new instance a different function object reference would be
    assigned to the property of the prototype. If all of those function
    objects are identical then the object would behave as expected but this
    would be inefficient.

    If any of them are exploiting their additional properties as inner
    functions then the function assigned to the prototype (and thus shared
    by all object instances) would be tied to a closure formed by the
    execution of the constructor for the last object instantiated. That
    would almost always be undesirable. See:-

    <URL: http://www.crockford.com/javascript/private.html >

    [1] ECMA 262 allows optimisation of inner functions but recent
    experimentation suggests that no browsers currently implement it.

    Richard.


    Comment

    Working...