我創建一個JS「庫」文件,但我想封裝它在它的全部對象中,以避免污染,其中包括文件創建JS庫,動態函數調用
的頁面的命名空間扭曲這是在圖書館內的功能,我需要通過名稱稱爲庫內的其他功能,例如使用window[]
下面的代碼只是一個示例,實際上有幾百個函數可以按名稱調用。這是由於我無法獲得window[]
來引用函數,這是由什麼引起的?
我已經試過了,在主機頁面:
<script src= "mylib.js"></script>
var oMyLib = new cMyLib(); //there will only ever be one 'instance' of this
在mylib.js一切都包含在一個功能:
function cMyLib() {
this.doStuff = function() {
someFunc(this); //call another function in the lib
}
// I tried it with prototypes also
// cMyLib.prototype.doStuff = function() {
// someFunc();
// }
function someFunc(that) {
var s='anotherFunc1'
var f = window[s]; //undefined!
f();
s='anotherFunc2'
f=window[s];
f();
}
function anotherFunc1() {}
function anotherFunc2() {}
}
只有全局函數顯示爲'window'的屬性,並且你不想這樣做(因爲這會污染名稱空間)。爲什麼你認爲你需要調用'window ['anotherFunc1']'那樣的? – Alnitak
riiight,這使得完整的感覺,拍額頭,我現在想着如果我不想使用eval,我不認爲實際上是壞的,我可以使數字引用的函數的數組。它的處理器模擬器,所以功能是指令,直接等於數字無論如何.. – martinc
你不能給一個函數一個數字的名字,但你可以做'this.insns = {}; this.insns [0x4c] =函數lda(...)' – Alnitak