1. 变量提升
无论声明在何处,都会被视为声明在函数的最顶部(不在函数内即在全局作用域的最顶部)
var 和let的区别
例:
var
function aa(){
if(false){
var test = "Hello World";
}else{
console.info(test);//undefined
}
console.info(test);//undefined
}
aa();
let
function aa(){
if(false){
let test = "Hello World";
}else{
console.info(test);//test is not defined
}
console.info(test);//test is not defined
}
aa();
var和const区别
例:var
var test = "lidian";
console.log(test);//lidian
test = "lidianmo";
console.log(test);//lidianmo
const
const test = "lidian";
console.log(test);//lidian
test = "lidianmo";
console.log(test);//Uncaught TypeError: Assignment to constant variable.
2. 模板字符串
var name = "lidian";
console.info("name:"+name);//name:lidian
console.info(`name:${name}`);//name:lidian
// es5
var msg = "Hi \
man!"
// es6
const template =
`<div>
<span>hello world</span>
</div>`
console.log(msg);
console.log(template);
var cludeStr = "ha";
console.log(cludeStr.repeat(3));//hahaha
console.log(cludeStr.includes("e"));//false
3.函数默认参数
function action(num = 200) {
console.log(num)
}
action() //200
action(0) //200
action(300) //300
4. 箭头函数
- 不需要function关键字来创建函数
- 省略return关键字
- 继承当前上下文的 this 关键字
例如:
1和2效果是一样的
var people1 = name =>'hello:' + name;
var people2 = function(name){
return `hello:${name}`;
}
PS:当函数有且仅有一个参数的时候,是可以省略掉括号的。当函数返回有且仅有一个表达式的时候可以省略{}
var people1 = name =>'hello:' + name;
var people2 = function(name){
return `hello:${name}`;
}
console.log(people1(123));
console.log(people2(456));
var people = (name, age) => {
const fullName = 'h' + name
return fullName
}
var people = function(name,age){
const fullName = 'h' + name
return fullName
}
5. 拓展的对象功能
- 对象初始化简写
//ES5
function people(name, age) {
return {
name: name,
age: age
};
}
//ES6
function people(name, age) {
return {
name,
age
};
}
- 对象中方法赋值,省略方法的冒号与function
const people = {
name: 'lux',
getName: function() {
console.log(this.name)
}
}
const people = {
name: 'lux',
getName () {
console.log(this.name)
}
}
- Object.assign() 同名的情况,后面会覆盖前面
//ES5
function people1(name, age) {
return {
name: name,
age: age
};
}
//ES6
function people2(sex, name) {
return {
sex,
name
};
}
const p1 = people1("lidian",12);
const p2 = people2("girl","lidianmo");
const obj = Object.assign({}, p1, p2);
console.info(obj);
- 解构赋值---更方便的数据访问方式
网友评论