0

I have following piece of code. In this code, I have a class called func. Inside func, I have 3 functions i.e. init, func1 and func2. Then I am calling init function before return object literal. So what happens is when I create new instance of this class using var f = new func() then it automatically calls the init function so I don't have call it manually. So its like constructor in other object oriented languages when a new instance of a class is created then constructor automatically gets called.

Here is the code

var func = function () {
    var a, b,
        init = function () {
            a = 1;
            b = 2;
        },

        func1 = function () {

        },

        func2 = function () {

        };

    init();

    return {
        func1: func1,
        func2: func2
    };
};

var f = new func();

Now I want to do the exact same thing as above in following scenario. That is I want the init function get automatically called whenever I call any function inside func object.

var func = {
    init: function () {

    },

    func1: function () {

    },

    func2: function () {

    }
}

func.func1();

Is it possible to make init function automatically called whenever I call any function inside func object in above scenario? If yes then How?

4

2 回答 2

3

您需要将所有对象的引用存储在数据结构中,例如字典,基本上每次调用函数时,您都需要查看字典并查看该对象之前是否已使用过,如果没有初始化它.
除此之外,如果未设置对象中的标志,我认为除了让每个函数都调用初始化程序之外没有其他办法。

于 2013-05-28T16:49:28.080 回答
0

这行得通,但我认为我不建议这样做,为什么不只使用 a class

jsFiddle 示例

var func = {
    a:0,
    b:0,
    init: function () {
        this.a = 1;
        this.b = 2;
        console.log('init');
    },

    func1: function () {
        console.log('func1');
        this.init();
        console.log(this.a);
        console.log(this.b)
    },

    func2: function () {
        console.log('func2');
        this.init();
        console.log(this.a);
        console.log(this.b)
    }
}

func.func1();
console.log("func1>" + func.a);
console.log("func1>" + func.b);
func.a = 0;
func.b = 0;
func.func2();
console.log("func2>" + func.a);
console.log("func2>" + func.b);
于 2013-05-28T16:50:32.440 回答