Q1-我有

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


我想以这种方式在HTML页面的架子中调用init函数

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


要么

shelf().init;


我该如何工作?,我在阅读了匿名的自执行函数,

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/

我需要文档和窗口对象,因为我将使用它来将组件动态添加到我的html页面

问题2-这是更好的方法还是我应该使用其他方法来确保模块化+重用?

最佳答案

在您的代码中,init不可从外部调用。我相信您正在寻找这样的东西:

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

10-06 11:58