1.函数的默认参数
function Fun(a=1,b=2) {} // 不传 a、b 参数的时候默认a=1,b=2。传了参数以传的参数为准
function Fun(a, b) { // ES5 定义默认参数的方法,但参数为 0 的时候,会有问题
let a = a || 1
let b = b || 2
}
2.模板对象(反引号 + ${})
let name = 'kobe'
let say1 = `My name is ${name}.` // 模板对象的使用例子
let say2 = 'My name is ' + name + '.' // ES5
3.解构赋值
const people = {
name: 'kobe',
age: '24',
sex: '男'
}
const {name, sex} = people // 解构赋值 name => kobe, sex => '男'
var name = people.name // ES5
var sex = peopele.sex
const list = [1, 2, 3, 4, 5]
const [a, , b, c, d] = list // a=>1, b=>3, c=>4, d=>5
4.增加的对象字面量
const name = 'kobe'
const age = 'age'
const obj = {
name,
[age]: 18,
message() {
console.log(this.name)
}
}
obj[age] = 21
const obj1 = {name: 'kobe', age: '18'}
let obj2 = Object.create(obj1)
obj2 = {sex: 'men'}
5.箭头函数。 this 指向器外层作用域的 this(指向定义时的this,非执行时的this)
var logUpperCase = function() {
var _this = this;
this.string = this.string.toUpperCase();
return function () {
return console.log(_this.string);
}
}
logUpperCase.call({ string: 'ES6 rocks' })();
var logUpperCase = function() {
this.string = this.string.toUpperCase();
return () => console.log(this.string);
}
logUpperCase.call({ string: 'ES6 rocks' })();
var promise1 = new Promise(function(resolve){
resolve(2);
});
promise1.then(function(value){
return value * 2;
}).then(function(value){
return value * 2;
}).then(function(value){
console.log("1"+value);
});
7.块作用域和变量申明方式 let、const (均在当前块作用域内有效)
const a = {num: '10'}
a.num = '12'
var myObject = {};
Object.defineProperty( myObject, "FAVORITE_NUMBER", {
value: 23,
writable: false,
configurable: false
});
8.class 类
class Point {
constructor(x, y) {
this.x = x;
this.y = y;
}
toString() {
return '(' + this.x + ', ' + this.y + ')';
}
}
var point = new Point(2, 3);
point.toString()
point.hasOwnProperty('x')
point.hasOwnProperty('y')
point.hasOwnProperty('toString')
point.__proto__.hasOwnProperty('toString')
9.Modules (模块)
import {name} from 'my-module'