(Javascript)关于“this”的说明在数组字面量内

(Javascript) Clarification on "this" within an array literal

本文关键字:数组 说明 Javascript 关于 this      更新时间:2023-09-26
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"作用域添加到数组文字中呢?

谢谢

不能,因为prototype是用来在类的每个实例之间"共享"成员的(以及它的后代,如果从未被重写的话)。这意味着你必须把它包装在一个函数中,以便它提供你需要的东西。

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已经被分配了。