4
var RPGConfig = (function() {
    var Constructor = function() {
        this.dir = "js";
        this.enginedir = "js/Engine";
    };
    Constructor.prototype = {
        include: [
            this.dir + "/Common.js",
            this.dir + "/Common/Class.js"
        ],
        test: function() {
            alert(this.dir);
        }
    };
    return Constructor;
})();
rpgConfig = new RPGConfig();
rpgConfig.test();
console.log(rpgConfig.include);

So, if I run rpgConfig.test(), the alert pops up with "js". Great! But, my rpgConfig.include shows up with "undefined" where this.dir should have printed "js" (as it did in test())...

So, how do I add "this" scope into an array literal?

Thanks

user3780225
  • 141
  • 7
  • 1
    See also [Self-references in object literal declarations](http://stackoverflow.com/q/4616202/1048572) – Bergi Sep 06 '15 at 19:02
  • 1
    Array and object literals don't have a scope. They're just inside a function scope, which is responsible for the `this` value - in this case your module IEFE. You'll have to move it inside your constructor. – Bergi Sep 06 '15 at 19:03
  • Perfect comments @Bergi. – Vidul Sep 06 '15 at 19:05

2 Answers2

3

You simply can't, because prototype is made to "share" members between every instance of a class (and its descendency if never overridden). Which means you have to wrap it in a function for it to give you what you need.

Constructor.prototype = {
    include: function () {
        return [
            this.dir + "/Common.js",
            this.dir + "/Common/Class.js"
        ];
    },
    test: function() {
        alert(this.dir);
    }
};
axelduch
  • 10,769
  • 2
  • 31
  • 50
1

The assignment to Constructor.prototype is evaluated first, before the constructor function. At the time it is evaluated, the constructor function has been declared, but not run, so the value of this.dir is undefined at that time.

The reason the test() function works is because it grabs the value of this.dir on demand every time you call it, so by the time you call it, this.dir has already been assigned.

chiliNUT
  • 18,989
  • 14
  • 66
  • 106