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

(Javascript) Clarification on "this" within 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);

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

那么,如何将 "this" 作用域添加到数组文字中?

谢谢

你根本做不到,因为原型是在 class 的每个实例之间为 "share" 成员创建的(如果从未被覆盖,则为它的后代)。这意味着您必须将它包装在一个函数中才能为您提供所需的东西。

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

Constructor.prototype 的赋值首先被评估,在构造函数之前。在求值的时候,已经声明了构造函数,但是没有运行,所以this.dir的值在那个时候是未定义的。

test() 函数起作用的原因是它每次调用时都按需获取 this.dir 的值,所以当你调用它时,this.dir 已经被分配。