云笔记阅读链接:http://note.youdao.com/groupshare/?token=44F78D26DFC6440185C4C353C8F82A43&gid=25271447
let
es5中没有块级作用域的概念,只有全局作用域和函数作用域,在if或者for循环定义变量的时候,导致变量变成全局作用域中变量;
let定义的变量只在let所在的块级作用域中有效,不会污染全局变量。
var a = [];
for (let i = 0; i < 10; i++) {
a[i] = function () {
console.log(i);
};
}
a[6](); // 6
const
==const==声明的变量不得改变值,意味着,const一旦声明变量,就必须立即初始化,不能留到以后赋值。
const的作用域与let命令相同,只在声明所在的块级作用域内有效。
if(true){
const Max = 5;
}
console.log(Max); // Uncaught ReferenceError: Max is not defined
==const==声明的变量也是不提升的,同样存在暂时性死区,只能在声明的位置之后使用。==同时不可重复声明。==
对于复合型的变量,变量名不指向数据,而是指向数据所在的地址。==const==命令只是保证变量名指向的地址不变,并不保证该地址的数据不变。
const a = [];
a.push('hello'); // 可执行 a[0]='hello'
a.length = 0 // 可执行, a = [];
a = ['dave']; // 报错
class类的概念
新的class类写法让对象原型的方法更加清晰,更像面向对象编程的语法。
class Animal{
constructor(){ // 构造方法
this.type = 'anmial'; // this关键字代表实例对象
}
says(say){
console.log(this.type + 'says' + say);
}
}
let animal = new Animal();
animal.says('hello'); // animal says hello
class Cat extends Animal{
constructor(){
super(); // 继承时必须,指代父类的实例
this.type = 'cat';
}
}
let cat = new Cat();
cat.says('hello'); // cat says hello
constructor内定义的方法和属性是实例对象自己的,而constructor外定义的属性和方法是所有实例对象可以共享的。
super关键字,它指代父类的实例(即父类的this对象)。子类必须在constructor方法中调用super方法,否则新建实例时会报错。这是因为子类没有自己的this对象,而是继承父类的this对象,然后对其进行加工。如果不调用super方法,子类就得不到this对象。
箭头函数(arrow function)
function(x, y) {
x++;
y--;
return x + y;
}
(x, y) => {x++; y--; return x+y} // es6语法
当使用箭头函数时,函数体内的this对象,就是定义时所在的对象,而不是使用时所在的对象。并不是因为箭头函数内部有绑定this的机制,实际原因是箭头函数根本没有自己的this,它的this是继承外面的,因此内部的this就是外层代码块的this。
class Animal {
constructor(){
this.type = 'animal'
}
says(say){
setTimeout( () => {
console.log(this.type + ' says ' + say)
}, 1000)
}
}
var animal = new Animal()
animal.says('hi') //animal says hi
setTimeout被调用的对象是window,所以如果不使用箭头函数,则setTimeout函数中的this对象指向的是window对象,this.type就为undefined,但是由于箭头函数没有自己的this,而是继承外面的this对象,故this对象指向Aniaml,所以this.type=animal
Template string
当需要插入大段的html代码到dom节点中,传统写法非常麻烦
$("#result").append(
"There are <b>" + basket.count + "</b> " +
"items in your basket, " +
"<em>" + basket.onSale +
"</em> are on sale!"
);
但是通过es6的语法则非常方便
$("#result").append(`
There are <b>${basket.count}</b> items
in your basket, <em>${basket.onSale}</em>
are on sale!
`);
用==反引号(`)来标识起始,用${}来引用变量==,而且所有的空格和缩进都会被保留在输出之中
Set和Map数据结构
set数据结构类似于数组,不同的是成员的值都是唯一的,没有重复的值
var s = new Set();
[1,2,3,4,5,3,2,1,8].map( x => {s.add(x)});
console.log(s); // 1,2,3,4,5,8
通过add方法向set数据结构中添加成员,但是不会添加重复的值
注:set数据结构提供了一种数组去重的方法
var arr = [1,2,3,4,5,3,2,1,8];
var arr1 = new Set(arr);
console.log(arr1); // 1,2,3,4,5,8
Set结构的实例属性有:
- Set.prototype.constructor: 构造函数,默认就是Set函数
- Set.prototype.size: Set实例成员变量的总数
Set结构的实例方法有:
- add(value): 添加某个值,返回set函数本身
- delete(value): 删除某个值,返回一个布尔值,表示删除成功或者失败
- has(value): 返回一个布尔值,表示改值是否为set的成员
- clear(): 清除set所有成员,没有返回值
Array.from方法可以将Set结构转为数组。
var items = new Set([1, 2, 3, 4, 5]);
var array = Array.from(items);
该方法提供了数组去重复的一种新方法
function dedupe(array) {
return Array.from(new Set(array));
}
dedupe([1, 1, 2, 3]) // [1, 2, 3]