博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
ES3之变量提升 ( hoisting )
阅读量:6692 次
发布时间:2019-06-25

本文共 1515 字,大约阅读时间需要 5 分钟。

JavaScript引擎在预编译时,会将声明(函数声明、变量声明)自动提升至函数或全局代码的顶部。但是赋值不会提升。

Because variable declarations (and declarations in general) are processed before any code is executed, declaring a variable anywhere in the code is equivalent to declaring it at the top. This also means that a variable can appear to be used before it's declared. This behavior is called "hoisting", as it appears that the variable declaration is moved to the top of the function or global code.

It's important to point out that the hoisting will affect the variable declaration, but not its value's initialization. The value will be indeed assigned when the assignment statement is reached:

例一

function hoisting(){    // 如果变量未提升,会报错 Uncaught ReferenceError: saint is not defined    console.log(saint);    var saint = 'Aioria';    console.log(saint);}hoisting();

例二

var saint = 'Orpheus';function hoisting(){    console.log(saint);    var saint = 'Aioria';    console.log(saint);}hoisting();

例三

function test(){    console.log(name,hello,welcome);    var name = 'Tom';    var hello = function(){        console.log('hello~');    };    function welcome(){        console.log('welcome~');    }    hello();    welcome();}test();

 

 

严格模式下,也会变量提升

'use strict';function hoisting(){    'use strict';    console.log(saint);    var saint = 'Aioria';    console.log(saint);}hoisting();

var 声明的变量会提升,let声明的变量不会提升。

function hoisting(){    console.log(saint);    let saint = 'Aioria';    console.log(saint);}hoisting();

 

 

转载于:https://www.cnblogs.com/sea-breeze/p/9006683.html

你可能感兴趣的文章
C语言中的注释
查看>>
Working with BeforeProperties and AfterProperties on SPItemEventReceiver
查看>>
JavaSE复习(一)继承多态与常用API
查看>>
php 上传文件名出现乱码
查看>>
Python 日期与时间
查看>>
CF467D Fedor and Essay 建图DFS
查看>>
[android] 手机卫士欢迎页检测更新
查看>>
[css] css3 中的新特性加强记忆
查看>>
创建并使用Linux桌面启动器(.Desktop文件) - firefox样例
查看>>
shiro 入门
查看>>
同步与异步
查看>>
leetcode------Spiral Matrix
查看>>
常用脚本
查看>>
打印出占用空间大于一定值的目录
查看>>
研究微信小程序
查看>>
Oracle常量
查看>>
PE文件头
查看>>
VC获取物理网卡的MAC地址
查看>>
Web学习>>一些专业名词
查看>>
找出由‘1’组成的孤岛
查看>>