OO style question

J

Joe Kelsey

When defining public methods, which style do you prefer:

style 1:

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

myObject.prototype.method = function ()
{
//...
}

or style 2:

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

myObject.prototype.method = function ()
{
//...
}
}

Can I use this.prototype within an object definition?

/Joe
 
R

Richard Cornford

Joe Kelsey said:
When defining public methods, which style do you prefer:

style 1:

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

myObject.prototype.method = function ()
{
//...
}

or style 2:

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

myObject.prototype.method = function ()
{
//...
}
}

Can I use this.prototype within an object definition?

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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Staff online

Members online

Forum statistics

Threads
474,079
Messages
2,570,574
Members
47,206
Latest member
Zenden

Latest Threads

Top