<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script src="../jquery-3.0.0.js"></script> </head> <body> <script> var handsome='你好!'; function handsomeToUgly(){ handsome="sssssss" console.log(handsome); /* var handsome1='ugly'; alert(handsome1);*/ } // handsomeToUgly(); (function handsomeToUgly1(a,b){ console.log(a); console.log(b); })("aaaaa","enhellow"); (function (a,b){ console.log(a); console.log(b); })("ceshi","ceshisss"); (function (a,b){ console.log(a); console.log(b); }("lingyixiefa","zaishishi")); // handsomeToUgly1(); </script> </body> </html>
这些写法在jquey插件中和webpack 打包的js内常见, 顺带着测试了下var 声明编译器置顶undefine .
声明提前
变量声明提前
在ES6之前,我们申明变量都是使用var
,使用var
申明的变量都是函数作用域,即在函数体内可见,这会带来的一个问题就是申明提前。
https://blog.csdn.net/dennis_jiang/article/details/106157904?utm_medium=distribute.pc_relevant.none-task-blog-2~default~baidujs_title~default-1.no_search_link&spm=1001.2101.3001.4242
以下是 两个var handsome 定义,函数体内handsome 又置顶声明了一次,给覆盖了函数外的声明,所以输出undefine
var handsome='你好!'; function handsomeToUgly(){ // handsome="sssssss" console.log(handsome); var handsome='ugly'; alert(handsome); } handsomeToUgly();
注释掉里边
var handsome='你好!'; function handsomeToUgly(){ // handsome="sssssss" console.log(handsome); /* var handsome='ugly'; alert(handsome);*/ } handsomeToUgly();
带着里边,在外边调用
var handsome='你好!';
function handsomeToUgly(){
// handsome="sssssss"
console.log(handsome);
var handsome='ugly';
console.log(handsome);
}
handsomeToUgly();
(function (){
console.log(handsome);
})();
作用域先找的外边的赋值. 声明和用是两码事.