Jack
Jack

Reputation: 7557

function not defined when I try to create an object and call function

I am trying to create an object and then call initialize function on that object. However I get initialize not defined. This is my code:

var SomeJSObj = function () {
    function Initialize() {
        $(document).ready(function () {
            alert('hello');
        });
    };
};

when I create a new object of SomeJSObj and call Initialize I get function not defined. Could anybody please help me track the error?

Upvotes: 0

Views: 74

Answers (5)

Samyak
Samyak

Reputation: 137

You can do it this way, Simple and easy way.

var SomeJSObj = function () {
    this.Initialize=function() {
        $(document).ready(function () {
            alert('hello');
        });
    };

};

var x = new SomeJSObj();
x.Initialize()

Upvotes: 1

David G
David G

Reputation: 96835

Firstly, $(document).ready should be outside the function definitions:

$(document.ready(function() {
    ...
});

The problem is that your methods should be defined on the object using the prefix this.:

this.Initialize = function() {
    ...
};

So all in all it comes to:

$(document).ready(function() {

    var SomeJSObj = function () {

        this.Initialize = function() {
             alert('hello');
        };

    };

});

And to call your methods you must create an instance:

var instance = new SomeJSObj(); // make sure this in in $(document).ready

and call the method:

instance.initialize(); // works

Upvotes: 1

mreq
mreq

Reputation: 6542

This is what you want. See the fiddle.

var SomeJSObj = function () {
    this.initialize();
};
SomeJSObj.prototype.initialize = function() {
  $(document).ready(function () {
      alert('hello');
  });
};
new ​SomeJSObj​();​

Upvotes: 0

James Allardice
James Allardice

Reputation: 166021

Initialize is currently not accessible outside of the SomeJSObj constructor. You need to expose it, either on each instance or on the prototype:

var SomeJSObj = function () {
    this.Initialize = function () {
        $(document).ready(function () {
            alert('hello');
        });
    };
};

On the prototype is more efficient, since only one copy of the function has to exist in memory, instead of one for each instance:

var SomeJSObj = function () {};
SomeJSObj.prototype.Initialize = function () {
    //Do stuff
};

Upvotes: 1

user1796666
user1796666

Reputation:

Should be like this since you want to make the Initialize function public:

var SomeJSObj = function () {
    this.Initialize = function() {
        $(document).ready(function () {
            alert('hello');
        });
    }
};

var t = new SomeJSObj();
t.Initialize();​

Upvotes: 1

Related Questions