作用域:
- 全局作用域
每个JS文件就是一个全局的作用域,它有且只有一个 - 局部作用域
每个独立的函数就是:局部作用域,平级的局部作用域不可相互访问 - 词法作用域
在函数内部可以访问的上级的作用域就是:词法作用域
闭包:
闭包是有权访问另一个函数作用域中变量的函数,举个栗子
function robot() {
var name = '小仙女'
return function() { console.log(`我是${name},喵 ~`)}
}
var kitty = robot()
注意:突出的是内部函数(匿名函数)能够访问外部函数中的变量
关于this
在 JavaScript 中的 this 总是指向调用它所在的的对象,并且 this 是在函数运行时自动生成的内部对象,因此只能在函数内部使用
有以下几个栗子:
- 全局的函数调用的时候,this 指向 window 对象,或者说函数定义时所在的作用域
var name = "global this";
function globalTest() {
this.name = "rename global this"
console.log(this.name);
}
globalTest(); // rename global this
console.log(name); // rename global this
- 如果函数作为对象的方法调用,this指向的是这个上级对象,即调用方法的对象
function showName() { console.log(this.name); }
var obj = {};
obj.name = "ooo";
obj.show = showName;
obj.show(); //ooo
- 构造函数中的this指向新创建的对象本身
function showName() { this.name = "showName function"; }
var obj = new showName();
console.log(obj.name); //showName function