1. let和const
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<script>
let:
//局部作用域
var a = [];
for (let i = 0; i < 10; i++){
a[i] = function () {
console.log(i)
}
}
a[2]() //2
a[5]() //5
//不会存在变量提升
console.log(a); //undefined
{
var a = 1;
var a = 10
}
console.log(a); //10
//变量不能重复声明
let a = 1;
let a = 10;
console.log(a); //10
// const:局部作用域,不会存在变量提升,不能重复声明,只声明常量,不可变的量
</script>
</body>
</html>
2. es6的箭头函数
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<script>
function add(x) {
return x
};
console.log(add(1)); //1
let add1 = function (x) {
return x
};
console.log(add1(10)); //10
let add2 = (x) => x;
console.log(add2(20)); //20
</script>
</body>
</html>
3. es6的对象
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<script>
let person1 = {
methods:{
fav:function () {
}
},
name:"ritian",
age:30,
fav:function () {
console.log(this); //this指当前的person1对象
console.log(this.name);
console.log(this.age);
}
};
person1.fav();
let person2 = {
name:"ritian2",
age:30,
fav:() => {
console.log(this); //this指定义person的父级对象(window)
console.log(this.name);
}
};
person2.fav();
let person3 = {
name:"ritian",
fav(){
console.log(this); //当前this,即person3
}
};
person3.fav()
</script>
</body>
</html>
4. es6的类
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>4</title>
</head>
<body>
<script>
function Vue(name,age) {
this.name = name;
this.age = age;
console.log(this.name); //ritian
console.log(this.age); //18
}
//基于原型给对象声明方法
Vue.prototype.showName = function(){
console.log(this.name);
};
Vue("ritian",18);
class Person{
constructor(name="ritian",age=18){
this.name = name;
this.age = age;
}
showname(){
console.log(this.name);
}
showage(){
console.log(this.age);
}
}
let V = new Person();
V.showname(); //ritian
V.showage(); //18
</script>
</body>
</html>