(Javascript) Explanation of "this" inside an array literal

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 (), a warning will appear with "js". Large! But, my rpgConfig.include appears with "undefined", where this.dir should print "js" (as it was in test ()) ...

So, how do I add the scope of this to the array literal?

thanks

+4
source share
2 answers

You simply cannot, because the prototype is made to "share" members between each instance of the class (and its descendant, if it is never redefined). This means that you must wrap it with a function so that it gives you what you need.

Constructor.prototype = {
    include: function () {
        return [
            this.dir + "/Common.js",
            this.dir + "/Common/Class.js"
        ];
    },
    test: function() {
        alert(this.dir);
    }
};
+3

Constructor.prototype . , , this.dir undefined .

, test(), , , , this.dir , this.dir .

+1

Source: https://habr.com/ru/post/1606172/


All Articles