3

I wanted to structure my javascript application with a modular pattern, as such:

APP = (function() {
    // Private stuff
    var _privateVariable = 'private',
        _priv = 'priv'

    _privateMethod = function(){ /* */ };

    // Exposed API
    return {
        publicVariable : 'public',
        publicMethod   : function(){ 
             return _privateVariable
        };
    }());

Then I want to be able to extend the application through plugin-like modules; for example, using jQuery:

$.extend(true, APP, (function() {
    // Child private stuff
    var _privateVariable = 'childPrivate',

    // Exposed API
    return {

    }()))

What I am trying to achieve is either one of the following:

  1. When calling APP.publicMethod() after extending it, I want to return 'childPrivate' and not 'private';
  2. Be able to access _priv from the extended exposed API.

In summary, I would like that the private variables defined in the parent module would be inherited in the child module as private members of the child.

Sunyatasattva
  • 5,619
  • 3
  • 27
  • 37
  • With that structure you can't do that. `var` declares variables in the local scope, so they won't accessible outside. You can make those variables public but follow private naming convention with `_` like you're doing. – elclanrs Sep 01 '13 at 01:44
  • Perhaps I could take a different approach/structure, then? I would really like to enjoy the privacy of those members, wouldn't it adding just an `_` prefix defeat the purpose of private variables altogether? – Sunyatasattva Sep 01 '13 at 01:46
  • There's no visibility in JavaScript, everything is controlled with closures. It's common to have public variables with an underscore to indicate it's private. You could try passing arguments around. – elclanrs Sep 01 '13 at 01:48
  • If you have any insight on how I could pass the arguments around to achieve this, I would be grateful, because I have been trying for the last couple of hours :) – Sunyatasattva Sep 01 '13 at 01:59
  • I played with some code a while ago to implement "private" members in JavaScript. Check here http://stackoverflow.com/questions/17008086/no-ways-to-have-class-based-objects-in-javascript/17008130#17008130. But still, it's not really "private" as in other languages. It's OK to have them public, no big deal in my opinion, at least in JS. – elclanrs Sep 01 '13 at 02:05

1 Answers1

0

With this structure you can't do that. Take a look at an awesome post by John Resig on how to achieve inheritance in javascript: http://ejohn.org/blog/simple-javascript-inheritance/

diegocstn
  • 4,447
  • 2
  • 20
  • 17