var num=10; console.log(num+10);
(function () { var num=10; console.log(num); })();
(function () { var num=20; console.log(num+10); }());
|
各个变量之间的数据互不干扰,可独立运行
同时沙箱也可以满足分别定义变量不冲突,同时在不同的沙箱内定义两个同名变量,互不冲突
(function () { var str="小白喜欢小黑"; str=str.substr(2); console.log(str); }());
(function () { var str="小明喜欢小红"; str=str.substr(2); console.log(str); }());
|
同时沙箱能解决函数名与变量名冲突的问题
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>title</title>
</head> <body> <div>这是div</div> <div>这是div</div> <div>这是div</div> <p>这是p</p> <p>这是p</p> <p>这是p</p> <script> var getTag = 10; var dvObjs = 20; var pObjs = 30 function getTag(tagName) { return document.getElementsByTagName(tagName) } var dvObjs = getTag("div"); for (var i = 0; i < dvObjs.length; i++) { dvObjs[i].style.border = "2px solid pink"; } var pObjs = getTag("p"); for (var i = 0; i < pObjs.length; i++) { pObjs[i].style.border = "2px solid pink"; } console.log(getTag); console.log(dvObjs); console.log(pObjs); </script> </body> </html>
|
可以看出,getTag
这里同时即是变量,也是函数,因此,将其封装到沙箱里
var getTag = 10; var dvObjs = 20; var pObjs = 30; (function () { function getTag(tagName) { return document.getElementsByTagName(tagName) } var dvObjs = getTag("div"); for (var i = 0; i < dvObjs.length; i++) { dvObjs[i].style.border = "2px solid pink"; } var pObjs = getTag("p"); for (var i = 0; i < pObjs.length; i++) { pObjs[i].style.border = "2px solid pink"; } }()); console.log(getTag); console.log(dvObjs); console.log(pObjs);
|
即可达到想要的,沙箱正是这种,内外之间互不干扰,又可以保持相对独立的方式