0

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页面的风格

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页面

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

+0

做进一步的了解模块化,我建议以下链接(来自同一本书):http://addyosmani.com/resources/essentialjsdesignpatterns/book/# modulepatternjavascript,http://addyosmani.com/resources/essentialjsdesignpatterns/book/#modularjavascript – bfavaretto

回答

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(); 
相关问题