如何使用自执行匿名函数中的对象?

时间:2013-06-28 16:41:21

标签: javascript function module anonymous-function self-executing-function

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 - 这是更好的方法,还是应该使用其他任何方法来确保模块化+重用?

1 个答案:

答案 0 :(得分: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();
相关问题