0
我有幾個模塊,我想從一個字符串實例化對象。 這通常是很容易當類/對象等都是在全球範圍內window
RequireJS從字符串名稱模塊的新實例
new window["MyClass"]()
隨着要求JS模塊不在window
範圍,他們還沒有在this
如果一個類中。
你知道我要求的範圍嗎?
define(['testclassb'], function(TestClassB) {
var TestClassA, testclassa;
TestClassA = (function() {
function TestClassA() {
console.log("A");
new this["TestClassB"](); #errors with undefined function
new window["TestClassB"](); #errors with undefined function
new TestClassB(); #works fine
}
TestClassA.prototype.wave = function() {
return console.log("Wave");
};
return TestClassA;
})();
testclassa = new TestClassA();
return testclassa.wave();
});
謝謝,星爺我不喜歡它TBH,但被實例化對象被確定通過套接字發送數據。所以我想避免一些令人討厭的if邏輯,所以我選擇了一個散列來將字符串映射到對象上http://pastie.org/7452137 – Rob 2013-04-11 09:57:42
是的,這就是你總能做的事情(什麼是正確的事情在這種情況下) :-) – Bergi 2013-04-11 10:23:17