Var (全局变量,函数变量)
var a = [];
for (let i = 0; i < 10; i++) {
a[i] = function () {
console.log(i);
};
}
a[6](); // 6
Let(块级变量,用来计数的循环变量避免泄露)
const monent = require('moment')
Const(块级常量,值不能改变,引用第三方库时声明的变量);
class Animal {
constructor(){
this.type = 'animal'
}
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
Class:定义类
constructor内定义的方法和属性是实例对象自己的,而constructor外定义的方法和属性则是所有实力对象可以共享的
extends关键字实现继承
Super:指代父类的this对象;子类必须在constructor方法中调用super方法,否则新建实例时会报错。因为子类没有自己的this对象,而是继承父类的this对象,然后对其进行加工
function(i){ return i + 1; } //ES5
(i) => i + 1 //ES6
function(x, y) {
x++;
y--;
return x + y;
}
(x, y) => {x++; y--; return x+y}
解决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
当我们使用箭头函数时,函数体内的this对象,就是定义时所在的对象,而不是使用时所在的对象。
$("#result").append(`
There are <b>${basket.count}</b> items
in your basket, <em>${basket.onSale}</em>
are on sale!
`);
用反引号(`)来标识起始,用${}来引用变量!
解构:
let cat = 'ken'
let dog = 'lili'
let zoo = {cat, dog}
console.log(zoo) //Object {cat: "ken", dog: "lili"}
let dog = {type: 'animal', many: 2}
let { type, many} = dog
console.log(type, many) //animal 2
default, rest
function animal(type = 'cat'){
console.log(type)
}
animal()
function animals(...types){
console.log(types)
}
animals('cat', 'dog', 'fish') //["cat", "dog", "fish"]