Вопрос

Q1 - I have

(function (document,window) {

var shelf = window.shelf = function (foo) {

    var init = function () {
        console.log("in init" + foo);
    };

    alert("in shelf.js "+ foo + "type" + typeof init);
};
})(document, window);

I want to call the init function in shelf in my HTML page in the style

var api=shelf("1234");
api.init();

Or

shelf().init;

How do i get this to work?, I read on anonymous self executing functions at,

Self-executing anonymous functions and closures ,

what is self-executing anonymous function or what is this code doing? ,

Why do you need to invoke an anonymous function on the same line? ,

http://markdalgleish.com/2011/03/self-executing-anonymous-functions/

I need the document and window objects as i will be using this to add components dynamically to my html page

Q 2 - Is this the better way or should I use anything else to ensure modularity + reuse?

Это было полезно?

Решение

In your code, init is not available to be called externally. I believe you're looking for something like this:

(function (document,window) {

var shelf = window.shelf = function (foo) {

    this.init = function () {
        console.log("in init" + foo);
    };

    alert("in shelf.js "+ foo + "type" + typeof this.init);
};
})(document, window);

var api = new shelf("1234");
api.init();
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top