Published
Edited
Aug 6, 2020
Insert cell
md`# javascript code迷云`
Insert cell
md`## 词法作用域`
Insert cell
scope = "global scope";
Insert cell
function checkscopeOne(){
var scope = "local scope";
function f(){
return scope;
}
return f();
}
Insert cell
function checkscopeTwo(){
var scope = "local scope";
function f(){
return scope;
}
return f;
}
Insert cell
md`因为 JavaScript 采用的是词法作用域,函数的作用域在函数定义的时候就决定了。`
Insert cell
checkscopeOne();
Insert cell
checkscopeTwo()();
Insert cell
md`**一旦设置了参数的默认值,函数进行声明初始化时,参数会形成一个单独的作用域(context)。等到初始化结束,这个作用域就会消失。**`
Insert cell
Insert cell
function fn1(x, y = x) {
console.log(y);
return y;
}
Insert cell
function fn2(y=x){
console.log(y);
return y;
}
Insert cell
md`- 调用函数f时,参数形成一个单独的作用域。在这个作用域里面,默认值变量x指向第一个参数x,而不是全局变量x`
Insert cell
fn1(2);// 2
Insert cell
md`- 参数y = x形成一个单独的作用域。这个作用域里面,变量x本身没有定义,所以指向外层的全局变量x。`
Insert cell
fn2();//1
Insert cell
md`## this指向`
Insert cell
name = 'global name';
Insert cell
obj=({
name:'local name',
sayName:function(){return this.name}
})
Insert cell
obj.sayName(); // obj.name => local name
Insert cell
objSayName = obj.sayName;
Insert cell
{
try{
objSayName(); // window.name => error
}catch(e){
console.error(e);
}
}
Insert cell
md`箭头函数`
Insert cell
objArrow=({
name:'local name',
sayName:function(){
return ()=>{return this.name} // 定义时绑定 : this=>objArrow
}
})
Insert cell
arrowSayName = objArrow.sayName();
Insert cell
arrowSayName();
Insert cell
md`箭头函数有几个使用注意点。
1. 函数体内的this对象,就是定义时所在的对象,而不是使用时所在的对象
2. 不可以当作构造函数,也就是说,不可以使用new命令,否则会抛出一个错误
3. 不可以使用arguments对象,该对象在函数体内不存在。如果要用,可以用 rest 参数代替
4. 不可以使用yield命令,因此箭头函数不能用作 Generator 函数

上面四点中,第一点尤其值得注意。this对象的指向是可变的,但是在箭头函数中,它是固定的。`
Insert cell
md`定义时所在的对象的解释:`
Insert cell
md`this指向的固定化,并不是因为箭头函数内部有绑定this的机制,实际原因是箭头函数根本没有自己的this,导致内部的this就是外层代码块的this。
正是因为它没有this,所以:
1. 也就不能用作构造函数
2. 以下三个变量在箭头函数之中也是不存在的,指向外层函数的对应变量:arguments、super、new.target
3. 当然也就不能用call()、apply()、bind()这些方法去改变this的指向。
`
Insert cell
md`
## 总结
1. 变量访问遵循作用域链
2. 函数作用域是作用域链的一部分
3. 注意分清函数作用域(变量)和this(值)
`
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more