ES3/5模拟实现ES6块级作用域方式探究
简述
在JavaScript编程中,当我们使用关键字var时,该变量是在距离最近的函数内部或是在全局词法环境中定义的,即函数作用域。这是JavaScript由来已久的特性,{}并不一定限制变量作用域的模式也困扰了许多从其他语言转向JavaScript的开发者。
随着前端工程的发展壮大ECMA也感觉JavaScript对于编写大型项目来说有些力不从心和不可编织的复杂度。于是ECMA吸纳了许多语言的优点并融入新版本的ES规范。
其中就包括定义块级作用域的关键字:const let
ES6块级作用域
{
{
let as = 1;
as = 2333;
}
function look(){
console.log(as);
}
// look();//R...Error
}如何用低版本模拟: try catch
try{
throw undefined
}catch(v){
try{
throw 1
}catch(as){
as = 2333;
}
function look(){
console.log(as);
}
// look();//R...Error
}如何用低版本模拟: try catch + with加强版
{
{
let a = 1;
let b = 2;
a = 2333;
b = 444;
}
function look(){
console.log(a);
}
// look();//R...Error
}
//=>>
try{
throw undefined
}catch(__e__){
try{
throw {a:1,b:2}
}catch(_$$scope$$_){
with(_$$scope$$_){
a = 2333;
b = 444;
}
}
function look(){
console.log(a);
}
// look();//R...Error
}如何用低版本模拟: 自调用函数版
;(function(){
(function(){
var as = 1;
as = 2333;
})();
function look(){
console.log(as);
}
look();//R...Error
})(); 相关推荐
leowzl 2020-08-15
明天你好 2020-08-03
idning 2020-08-03
chenlxhf 2020-06-25
Jonderwu 2020-06-14
shikailonggy 2020-06-05
shangs00 2020-05-09
wanff0 2020-05-04
ChinaGuanq 2020-05-01
whbing 2020-04-21
hyxinyu 2020-04-18
sunlizhen 2020-04-17
amberom 2020-03-28
zgwyfz 2020-03-28
XCMercy 2020-03-26
ThinkingLink 2020-02-29
Livis的开发之路 2020-02-28