网络上的许多不同文章都宣称在设计模块时使用全局导入非常棒(类似于jQuery)。
所以,做这样的事情......
import requests
import re
import bs4
def verse(book, chapter):
html = requests.get("http://www.holybible.or.kr/B_NIV/cgi/bibleftxt.php?VR=NIV&VL={}&CN={}&CV=99"
.format(book, chapter)).text
bs = bs4.BeautifulSoup(html, 'html5lib')
ol = bs.findAll('ol')
section_cnt = int(ol[-1].attrs['start']) + len(ol[-1].findAll('li')) - 1
w = re.search(r'(?<=height=12>\s<b>)(\d+\s)?[a-zA-Z]+\s[0-9]+', html).group()
w2 = re.search(r'(?<=height=12>\s<b>(\d+\s)?[a-zA-Z])+\s[0-9]+', html).group()
print(w, 'has', w2, 'chapters', section_cnt, 'verses')
if __name__ == '__main__':
verse(1, 27)
...意味着我可以使用以下内容调用函数:
(function(globalVariable){
globalVariable.printStuff = function(){
console.log(‘Hello World’)
};
}(globalVariable));
问题是,无论何时我在控制台中运行它,我都会得到:
globalVariable.printStuff();
我的问题是,我究竟需要在哪里声明这个变量,以便我可以让它工作?
答案 0 :(得分:1)
对于这样一个真正简单的模块,你不需要任何IIFE。只需写一个对象文字:
var globalVariable = {
printStuff: function() {
console.log('Hello World');
}
};
globalVariable.printStuff();
如果要使用IIFE范围,则仍需要在某处创建对象。这可能在模块内部或外部:
var globalVariable = (function() {
var module = {};
var localVariable = 'Hello World';
module.printStuff = function() {
console.log(localVariable);
};
return module;
}());
globalVariable.printStuff();
var globalVariable = {};
(function(module) {
var localVariable = 'Hello World';
module.printStuff = function() {
console.log(localVariable);
};
}(globalVariable));
globalVariable.printStuff();
答案 1 :(得分:0)
对于浏览器window对象是存储所有全局变量的对象。下面的代码显示了具有全局变量的IIFE的基本实现。
//Set a variable 'globalVariable' in the window object
window.globalVariable = 10;
//Access the global variable 'globalVariable' in IIFE
(function(globalVariable) {
console.log(globalVariable);
})(globalVariable);