(Javascript)澄清数组文字中的“this”

时间:2015-09-06 18:38:41

标签: javascript arrays literals

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

所以,如果我运行rpgConfig.test(),警告会弹出“js”。大!但是,我的rpgConfig.include显示为“undefined”,其中this.dir应该打印“js”(就像它在test()中所做的那样)......

那么,如何将“this”范围添加到数组文字中?

由于

2 个答案:

答案 0 :(得分:3)

你根本无法做到,因为原型是为了共享"类的每个实例之间的成员(如果从未被覆盖,则为其下降)。这意味着你必须将它包装在一个函数中,以便为你提供所需的东西。

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

答案 1 :(得分:1)

首先在构造函数之前评估对Constructor.prototype的赋值。在评估时,构造函数已声明但未运行,因此this.dir的值在此时未定义。

test()功能的工作原因是因为每次调用它时都会根据需要获取this.dir的值,因此当您调用它时,this.dir已被分配。