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();
0

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Seams really complicated, could I just use the prototype chain somehow?
@AdrianMcCool: You could make f2.history inherit from f2, but that hardly makes any sense to me
Modules/submodules and inheritance are very different concepts. Inheritances makes little sense without instantiation.
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();

1 Comment

OK. But why would you want to "override" an object literal? There is only one f2 (example)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.