一、变量提升
1、
console.log(a, b, c);
var a = 12,
b = 13,
c = 14;
function fn(a) {
console.log(a, b, c);
a = 100;
c = 200;
console.log(a, b, c);
}
b = fn(10);
console.log(a, b, c);
结果:undefined undefined undefined
10 13 14
100 13 200
12 undefined 200分析: 由执行栈执行顺序从上而下可知第一行打印都是undefined
执行fn时,a 为内部参数,声明内部私有a为10;没有b,使用外部b=13;同理c=14;
a赋值100;c赋值200; 所以打印 100,13,200;
因为函数执行默认返回undefined,赋值给b, b结果为undefined
此时a仍是12, c因为函数内修改了全局的c,所以c为200
2、
var i = 0;
function A() {
var i = 10;
function x() {
console.log(i);
}
return x;
}
var y = A();
y(); // i =10;
function B() {
var i = 20;
y();
}
B(); // 10
结果: 10, 10
分析: 函数x创建在了A函数中,在A作用域中i为10;执行函数x的时候,内部没有i,去外部作用域查找i=10; 第二个B执行时,y执行外部作用域仍是A创建的,所以i仍是i=10;
3、
var a=1;
var obj ={
name:"tom"
}
function fn(){
var a2 = a; // a2 = 1;
obj2 = obj; // obj2 = obj = {name:'tom'}
a2 =a; // a2 = 1
obj2.name ="jack"; // obj2.name = "jake"
}
fn();
console.log(a); // 1
console.log(obj); // {name:'jake'}
结果:1 , { name: Jake}
分析,堆引用的问题
4、
var a = 1;
function fn(a){
console.log(a) // function a(){}
var a = 2;
function a(){
}
}
fn(a);
结果为:function a(){}
考察函数作用域内变量提升,首先var a;初始化参数a=1;赋值为2;赋值为函数function a(){}
5、
console.log(a); // undefined
var a=12; // 声明 var a; fn(){...};
function fn(){
// 执行 函数作用域中私有变量a变量提升,打印a为undefined
console.log(a);
var a=13; // 函数内a赋值为13
}
fn();
console.log(a); // 函数外EC(G)变量a仍为12
结果为 undefined 、 undefined 、 12 , 分析如上
6、
var foo='hello'; // EC(G) var foo;
(function(foo){
// 自闭合函数执行,传入foo = "hello"
console.log(foo); // 函数初始化私有变量foo = "hello" , 打印"hello"
var foo=foo||'world'; // var foo = "hello" foo赋值操作,
console.log(foo); // foo 仍为“hello”
})(foo);
console.log(foo); // foo 'hello'
结果: “hello”,“hello”,“hello”
7、
{
function foo() {
}
foo = 1;
function foo() {
}
foo = 2;
}
console.log(foo);
结果为1 ?
分析: 考察块机作用域的变量提升
老版本浏览器,全局上下文中变量提升的时候,不论条件是否成立,或者是否出现在大括号中(排除函数和对象大括号)对于function来说仍然是声明加定义,
高版本浏览器中,为了保证语意的准确性,条件不成立不赋值,或者执行的时候在全局下,只声明不赋值,
{
console.log(foo)
function foo() {1}
console.log(window.foo())
foo = 1;
function foo() {2}
foo = 2;
}
8、
二、数据类型和基础知识作业
1、
let result = 100 + true + 21.2 + null + undefined + "Tencent" + [] + null + 9<