Example of situation that needs declaring a method inside the constructor function instead of declaring it as a prototype method

Go To StackoverFlow.com

2

I understand that prototype method is shared by all instances of an object in JavaScript.

I can't think of a practical example when you will need the other situation—declaring the method inside the constructor function and thus making every instance of the object having it's own instance of the method. Can you provide a case for this?

2012-04-05 16:18
by Windom Earle
You opened Pandora's box, son - Chris Baker 2012-04-05 16:45
At least I hope it will be fruitful : - Windom Earle 2012-04-05 16:49


2

The primary use is emulating private fields. See my answer here for an example:

Declaring javascript object method in constructor function vs. in prototype

2012-04-05 16:22
by Tim Down
It should be noted this doesn't have any real advantage. It incurs a non-negligible performance penalty and the only reason to use it personal coding styl - Raynos 2012-04-05 16:23
@Raynos: I disagree. Keeping variables private rather than exposing them as public object properties can lead to more robust code - Tim Down 2012-04-05 16:26
But they are not private :. It doesn't increase robust-ness at all what so ever - Raynos 2012-04-05 16:29
How do you mean "they aren't private". I know that you know what the term "private" means. We all know you can look at the source code and see them, but you can't call them externally in code, and that is the intention. It is a tool, and it has a place - Chris Baker 2012-04-05 16:32
@Chris Why do you value not being able to call them externally in the code? You can find and manipulate their value through the use of eval hacks in certain browsers that have proprietary features. There are always workarounds to manipulate closure state externally. Using internal properties like this._prop has the same benefit of letting your user know that the state of that property should not be alternated - Raynos 2012-04-05 16:34
@Raynos: Being available via eval hacks is very, very different to being available via a public property - Tim Down 2012-04-05 16:36
@TimDown what is different about it? The state can still be publically modified, which means it's not robust - Raynos 2012-04-05 16:38
It isn't that I want to stop them. We're cross-commenting all over the place here, but I said it in my other comment -- I am not going to call a method externally that doesn't make sense to call externally. I am not going to do it in PHP or javascript because... why would I? So taking that into account, no private anything makes sense, why bother? But, I like a clean API, I like to look at the public methods and properties and only see a list of things that should be dealt with externally. It is an organizational tool with value as such. It is possible to over-use or misuse, too - Chris Baker 2012-04-05 16:39
@Raynos: I'm not particularly concerned about whether it's theoretically possible to get at these "private" variables. Anyone working with my code is not going to be remotely interested in eval hacks. Keeping the properties on my object down to just those that are designed to be manipulated is the ideal: it makes the object easier to inspect in standard tools and it protects it from inadvertent breakage. Do you disagree that those are good things? I acknowledge that it comes at a cost, hence my comment about it being a trade-off - Tim Down 2012-04-05 16:55
@TimDown protecting from inadvertent breakage isn't of value, it doesn't break if people use it correctly, if people use it incorrectly then it's their problem. Making an object easier to inspect is of value but neglible because if an object is difficult to inspect you need smaller objects anywa - Raynos 2012-04-05 16:58


1

but I can't think of a practical example when you will need the other situation

That's because there is no practical example.

Declaring functions inside the constructor is a known bad practice due to incurring unnecessary performance penalties.

It should also be noted that prototypes are awesome because they encourage extensibility, flexibility and monkey patching. Meaning that you can fix someone else's objects because everything can be intercepted and manipulated.

Closures are like frozen objects, they remove flexibility from you and are a nightmare to manipulate, wrap or alter.

It should be noted you don't need to use prototypes and can use functions instead if that pleases you

function cake(fruits, chocolate, size) {
    return {
        slice: function () {
            return cakeSliceList(this)
        },
        toString: function () {
            return "A lovely cake containing " + fruits.toString()
                + ", " + chocolate.toString()
        },
        weight: function () {
            return size * CAKE_SIZE + fruits.weight() + chocolate.weight()
        }
    }
}

A functional style is valid, combining the functional style together with prototypes get's rather silly, rather quickly.

2012-04-05 16:22
by Raynos
Somewhat dogmatic. It's a trade-off between performance versus clarity and convenience. Performance doesn't always win - Tim Down 2012-04-05 16:23
@TimDown it offers no clarity nor does it offer any convenience. Compared to alternative - Raynos 2012-04-05 16:24
than why it's not bad in PHP? Because of the private,protected variables - Windom Earle 2012-04-05 16:24
@WindomEarle I don't know about how PHP works, if people do the same thing in PHP then they are doing it wrong as well - Raynos 2012-04-05 16:25
well in php you have classes where you describe your properties and methods and with every instance of the class you have separate instances of the methods as well. so it's like the second situation in javascript that i'm talking about. at least that's how I think it works - Windom Earle 2012-04-05 16:26
Raynos, you're following the party line to a ridiculous extreme here. I am with you on blackCoffee, but declaring private properties has a value, and using them in PHP is not "wrong". There is a value to doing it in javascript, -even if you're only doing it out of personal preference - Chris Baker 2012-04-05 16:30
@Chris Real private properties in PHP are of value, emulating privacy using closures is of no practical value. If that's your personal coding style then you can use it, just be aware that your coding style has performance penaltie - Raynos 2012-04-05 16:32
@Raynos can you go into more detail on performance penalties? I know that closured/private functions incur creation cost, and also more memory. But where do they live on the scope chain? A lookup to a prototype function is at least 1 jump down the scope chain. How many is it to reach a closure - Matt 2012-04-05 16:34
The "no practical value" statement is the part that is catching no flies. How can you make such a blanket statement not knowing use cases? What is "practical value"? I like my object API to be tidy, and I like to segment my code into reusable pieces. I don't want to see a drawInterface method in the public API, even though I am never going to invoke it externally because I know not to. I make it private through constructor closure, now I don't see it in the public interface of that object. That, to me, is of practical value - Chris Baker 2012-04-05 16:35
@Matt - the performance penalty is in reference count. A constructor closure creates a new entity in memory, whereas a prototype method only causes one memory entity to exist - Chris Baker 2012-04-05 16:36
@Chris that problem is trivially solved, use a object logger that doesn't show any properties that start with _Raynos 2012-04-05 16:37
An object logger has performance penalties and is of no practical value. Erm... I love you Raynos - Chris Baker 2012-04-05 16:42
@Chris regarding performance, the point I was trying to make is that there is a initialization/memory penalty, but is there a lookup bonus? Based on location in scope chain - Matt 2012-04-05 16:46
@Matt lookup bonus is implementation specific, in an ideal implementation it should favour prototypes marginall - Raynos 2012-04-05 16:47


1

I agree with @Raynos to an extent - it does feel like an unnecessary and futile practice to implement private state at the cost of efficiency.

In general it’s necessary to create functions when any sort of state-binding is required. So it could be of practical value when you need to pass functions around that refer explicitly to the object state. If you’re going to incur the penalty each time you create a state-bound function then you are at a plus if you bind it just once in the constructor and reference that single bound function rather than creating it multiple times.

State binding is sometimes necessary by design choices out of your own hands. It would make sense for example to create state-bound event handlers for an object on initialisation.

2012-04-05 16:52
by Matt Esch
It should be noted Function#bind can be used effectively to bind methods from the prototype to the instance rather then using closures - Raynos 2012-04-05 17:01
this is interesting. thanks - Windom Earle 2012-04-05 17:28


0

If you are using closures anywhere in your object, and need to reference them inside your function. Or, alternatively, if you specifically want to make your function "private".

Of course, this begs the question of under what circumstances you want to use closured variables. The 'private' argument may popup here again. Additionally, here is a discussion as to some common uses of closures.

2012-04-05 16:27
by Matt
Ads