0

How can I inherit an objects variables within namespace(scope)?

var f2 = {
   a: 'test'
}

f2.history = {

  load: function(){ alert(this.a); }

}

// Turns out Undefined
f2.history.load();
Adrian McCool
  • 143
  • 2
  • 12

2 Answers2

1

There is no link between f2.history and f2. More generally there is no link between a property value and its holder.

You could call it like this :

f2.history.load.call(f2);

Or you could declare your objects with a factory :

var f2 = (function(){
    var self = {
        a: 'test'
    };
    self.history = {
        load: function(){ alert(self.a); }
    };
    return self;
})();

This would allow

f2.history.load();

Another variant would let you define the submodules in a more separated way :

var f2 = {
    a: 'test'
};
(function(f){
    f.history = {
        load: function(){ alert(f.a); }
    }
})(f2);

The advantage of this last construct is that it's easy to declare sub-modules in different files.

Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
1

use the namespace, f2, not this.

 load: function(){ alert(f2.a); }

works


var f2 = {
    a : 'test',
    init: function(a) {
        if (a) this.a = a; //set a, if a is defined
    },
};
function history(a) {
    function F() {};
    F.prototype = f2;
    var f = new F();
    f.init(a);
    load = function() {
        alert(f.a);
    }
    return this;
}

var h1 = history();
h1.load(); //alerts "test"

var h2 = history('history'); 
h2.load(); //alerts "history"

//but now h1 also holds history
h1.load();
davidkonrad
  • 83,997
  • 17
  • 205
  • 265