将索引值传递给javascript命名空间数组

passing an index value to a javascript namespaced array

本文关键字:javascript 命名空间 数组 索引 索引值 值传      更新时间:2023-09-26

作为joomla网站的一部分,我在几个文件中有相当多(>20)个相当长的英语句子数组(~50个元素)。jquery点击事件将访问这些数组,该事件将显示句子作为英语单词使用的示例。为单个句子生成数组索引的点击事件功能正在发挥作用。我想使用模块模式为数组命名。根据
http://www.2ality.com/2011/04/modules-and-namespaces-in-javascript.html,模块定义可以分布在多个位置。从模块可伸缩性的角度来看,这将非常有用。我修改了上面文章中的一个模块,因此:

var namespace = function() {
     var index = 2;    // for example
     var arr = ["the boy is going home",
                "You and I are friends",
                "He has a book of mine"]; 
    return {
        get values() {
            return arr[index];
        }
    };
}();
console.log(namespace.values);

这就行了。但是,我想将数组索引传递给模块,并让它返回相应的文本。如何做到这一点?

var namespace = function() {
     var arr = ["the boy is going home",
                "You and I are friends",
                "He has a book of mine"]; 
    return {
        values: function(index) {
            return arr[index];
        }
    };
}();
console.log(namespace.values(1));

因此,当IIFE返回namespace的objet属性时,我们将values设为函数(method)并传入index。一旦IIFE执行,你可以这样想;

var namespace =  {
    values: function(index) {
        return arr[index];
    }
}

但具有初始化的CCD_ 6阵列。

试试这个:

namespace = function() {
     this.index = 2;    // for example
     this.arr = ["the boy is going home",
                "You and I are friends",
                "He has a book of mine"]; 
};
namespace.prototype.getValueAt = function(index){
   return this.arr[index];
};
console.log(namespace.getValueAt(0));