2013-05-07 64 views
-1

如何在JavaScript中保存/重用对象?启动JavaScript对象并将其保存到变量

if (typeof window.Test == "undefined") window.Test = {}; 
if (typeof Test == "undefined") Test = {}; 

Test.Object1 = function() { 
    var obj = { 

     init: function(msg) { 
      console.log(msg); 
     }, 

     EOF: null 
    }; 

    return obj; 
}(); 

Test.Test = function() { 
    var obj = { 

     init: function() { 
      var obj1 = Test.Object1.init('Object 1 initialized'); 
      console.log(obj1); 
     }, 

     EOF: null 
    }; 

    return obj; 
}(); 

Test.Test.init(); 

console.log(obj1)回报undefined

var obj1 = new Test.Object1();产生TypeError: Test.Object1 is not a constructor

+0

你从未定义'测试'。你的代码中有'Test = {}'的地方吗? – romo 2013-05-07 16:29:21

+0

是的,我做了,对不起忘了包括它 – keeg 2013-05-07 16:32:02

回答

1

init只是调用console.log并返回undefined。您将init(再次,undefined)的结果存储到obj1中,并且控制台忠实地向您报告该值。

也许你想做的事:

var obj1 = Test.Object1; 

因为Test.Object1obj你的第一个匿名函数中的价值。

或许你想做的事:

Test.Object1 = function() { 
    var obj = { 

     init: function(msg) { 
      console.log(msg); 
      return this; 
     }, 
... 

使init返回非undefined值。

+0

'var obj1 = Test.Object1;'是我正在寻找的,我加了'()'括号,杜。谢谢! – keeg 2013-05-07 16:38:49

相关问题