1.变量提升 var x = 2; function test(){ console.log(x) var x = 1; } ==>运行程序报错,在test()函数中,x被提升到了顶部声明,相当于 var x = 2; function test(){ var x; console.log(x) x = 1; } 2.函数提升 a)函数声明可以提升 test(); function test(){ console.log(123); } b)函数表达式不能提升 test(); var test…
参考了这篇文章 http://www.jb51.net/article/30719.htm var v='Hello World'; (function(){ console.log(v); })() 输出: Hello World 但是 var v='Hello World'; (function(){ console.log(v); var v = 'hi'; })() 输出: undefined 这里面隐藏了一个陷阱-----JavaScript中的变量提升(Hoisting).在JS中,…
Chapter4: Hoisting 变量附加到哪个层次的scope,由它们在哪里和如何声明(let, var)来决定. Function scope/Block scope都有相同的法则:任何变量在一个scope内声明,则这个变量附加到这个作用域上. 但有一个细节问题:当声明declarations出现在一个作用域中的不同的位置的时候,scope附加如何与declarations协作? Chicken or The Egg? temptation: a strong desire to hav…
在上一篇提到了JS有三种声明变量的方式,分别是var.const及let,var和const let最大区别就是范围(scope)的限制.所以在这一篇我们会详谈何谓范围链及他们的复写优先级. 范围Scope 我们先来看一个例子: var globalVar = 'global': function scopeFun(){ globalVar =“change in scopeFun”: console.log(“1.”,globalVar)://1.change in scopeFun var…
来看如下代码: function HelloJS(){ var array = [1,2,3,4,5]; for(var i in array){ } alert(i); } HelloJS(); alert(i); 此段代码运行后先执行HelloJS();,会先输出4,然后再执行alert(i);,执行alert(i);时会报i is not defined的错误. 根据变量提升,这段代码等同于如下代码: function HelloJS(){ var i: var array = [1,2,…
Ref: 深入理解js的变量提升和函数提升 一.变量提升 简直就是es5的遗毒! console.log(global); // undefined 竟然能打印?因为变量提升,下一行就有定义 var global = 'global'; console.log(global); // global function fn () { console.log(a); // undefined 竟然能打印?因为变量提升,下一行就有定义 var a = 'aaa'; console.log(a); //…
<script> function test(){ console.log(a); console.log(foo()); var a=1; function foo(){ return 2; }; }; </script> 执行结果为:undefined和2: 变量声明在js中需要提升,所以以上代码相当于以下代码: <script> function test(){ var a; function foo(){ return 2; }; console.log(a);…
Explain event delegation Event delegation allows us to attach a single event listener, to a parent element, that will fire for all children matching a selector, whether those children exist now or are added in the future.the underlying cause is brows…
只能是粗浅的,毕竟js用法太灵活. 首先抛概念:闭包(closure)是函数对象与变量作用域链在某种形式上的关联,是一种对变量的获取机制.这样写鬼能看懂. 所以要大致搞清三个东西:函数对象(function object).作用域链(scope chain)以及它们如何关联(combination) 首先要建立一个印象,在js中,几乎所有的东西可以看作对象,除了null和undefined.比如常用的数组对象.日期对象.正则对象等. var num = 123; // Number var ar…
Hoisting is JavaScript's default behavior of moving all declarations to the top of the current scope (to the top of the current script or the current function). function number() { return 1; } (function() { try { number(); } catch (ex) { console.log(…
原文:你不知道的js系列 先有鸡还是先有蛋? 如下代码: a = 2; var a; console.log( a ); 很多开发者可能会认为结果会输出 undefined,因为 var a 在 a = 2 后面,好像变量似乎被重新定义了,所以结果会是默认值 undefined. 然而,正确结果是 2. 下面这段代码,a 在 定义之前被引用.不会抛出错误,也不会输出 2 . console.log( a ); var a = 2; 结果输出 undefined. 编译器 回忆一下第(一)节中的内…