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(); 
相關問題