Home > Web Front-end > JS Tutorial > body text

javascript自执行函数之伪命名空间封装法_javascript技巧

WBOY
Release: 2016-05-16 18:13:28
Original
1324 people have browsed it

自执行函数:自动执行的函数。它在被解释时就已经在运行了。一般函数都是在被调用时才会执行的。
自执行函数的一般格式:(function() { 函数体 })();
而且,自执行函数中一般都会有一个function() {}形式的匿名函数。

下面的代码在window对象中创建一个命名空间 mySpace,并把自执行函数中的方法封装在mySpace命名空间之下,以便于我们调用这个自执行函数中的一些功能。

复制代码 代码如下:

(function() {
//根据id获取对象
function $(id) { return document.getElementById(id); }

//内部函数,在外层是不可以调用的
function _setStyle(id, styleName, styleValue) {
$(id).style[styleName] = styleValue;
}

//创建伪命名空间
window.mySpace = {};

//将内部函数_setStyle封装在mySpace命名空间内
//调用时,使用window.mySpace.setStyle(id, styleName, styleValue)
window.mySpace.setStyle = _setStyle;
})();

//下面是测试代码
window.onload = function() {
//将id为test的对象的文字颜色设置为红色
window.mySpace.setStyle("test", "color", "#f00");
}

那么这种封装方式到底有何好处呢?

当然就是保护了自执行函数内的方法、变量、属性等。这样代码更加安全了。

如果不使用这种方法,那么,下面的方法也可以实现的。
复制代码 代码如下:

window.mySpace = {};
window.mySpace.$ = function(id) { return document.getElementById(id); }
window.mySpace.setStyle = function(id, styleName, styleValue) {
window.mySpace.$("test").style[styleName] = styleValue;
}
//下面是测试代码
window.onload = function() {
window.mySpace.setStyle("test", "backgroundColor", "#f00");
window.mySpace.setStyle("test", "color", "#fff");
}

上面的代码和自执行函数实现的功能其实是一样的。

比较之后,我们可以发现,第二方法更加的直观,易于理解。但是少了封装过程,代码完全裸露在外。
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!