简体   繁体   中英

“Private” properties inheritance in Javascript

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.

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/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM