Om3ga
Om3ga

Reputation: 32893

want initialize function get called automatically when object is used

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?

Upvotes: 0

Views: 1040

Answers (2)

Gabe
Gabe

Reputation: 50503

This works, I don't think I'd recommend doing this though, why not just use a class?

jsFiddle Example

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);

Upvotes: 0

aaronman
aaronman

Reputation: 18751

You would need to store the references of a all the objects in a data structure, like a dictionary, basically every time you call a function you would need to go through the dictionary and see if the object has been used before, if not initialize it.
Other than that I see no way to do it short of having every function call the initializer if a flag in the object is not set.

Upvotes: 3

Related Questions