启动并将JavaScript对象保存到变量

时间:2013-05-07 16:27:30

标签: javascript oop

如何在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

1 个答案:

答案 0 :(得分:1)

init只需致电console.log并返回undefined。您将init(再次,undefined)的结果存储到obj1,控制台会忠实地向您报告该值。

也许你想这样做:

var obj1 = Test.Object1;

因为Test.Object1在您的第一个匿名函数中的值为obj

或许你想这样做:

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

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

以便init返回非undefined值。