🍅程序员小王的博客:程序员小王的博客
🍅 欢迎点赞 👍 收藏 ⭐留言 📝
🍅 如有编辑错误联系作者,如果有比较好的文章欢迎分享给我,我会取其精华去其糟粕
🍅java自学的学习路线:java自学的学习路线
一、前提:
- ECMAScript6新语法
ECMAScript版本的新语法,不是所有浏览器都兼容,有些浏览器兼容局部
二、ECMAScript的新语法
1、变量定义
5版本:var 变量名:变量使用范围不明确
<script>
for (var i = 0; i < 10; i++) {
console.log("in:"+i)
}
console.log("out:"+i);
</script>
6版本: let const:声明变量
- let 变量名 用于声明局部变量 作用范围:从定义行开始到所在代码块结束
<script>
for (let i = 0; i < 10; i++) {
console.log("in:"+i)
}
console.log("out:"+i);
</script>
- const修饰的值不可变(相当于java中的final)
- const修饰的对象地址不可以变,但是属性可以变,可以修改属性
const student={id:1,name:"王恒杰"}
console.log(student);
//const修饰的对象地址不可以变,但是属性可以变,可以修改属性
student.id=2;
console.log(student)
//增加属性age
student.age=18;
console.log(student)
2、箭头函数
- 使用场景:匿名函数作为函数的参数
- 语法:()=>{}等价于
function(){}
简化了function
- 5版本:函数 function xx(){}
- 6版本:箭头函数
//箭头函数
function test(func) {
func(1);
}
//5版本:函数 function xx(){}
test(function (i) {
alert(i);
})
//6版本:箭头函数 ()=>{函数体}
test((i)=>{
alert(i);
})
注意:
(1)函数只有一个参数时,()可以省略不写,参数是多个或者没有参数需要加上小括号
(2)函数体中只有一行代码,{}也可以省略
(3)箭头函数没有自己的this,如果在箭头函数中的this,代表当前vue对象,不代表当前函数
3、模板字符串 ``
在定义变量时 变量中包含html标签可以使用
// 模板字符串
let html="<button @click='test1("+'name'+")'>点我</button>"
+"<button @click='test1("+'name'+")'>点我</button>"
+"<button @click='test1("+'name'+")'>点我</button>"
+"<button @click='test1("+'name'+")'>点我</button>"
console.log(html);
//模板字符串
let html1=`<button @click='test1("+name+")'>点我</button>
<button @click='test1("+name+")'>点我</button>
<button @click='test1("+name+")'>点我</button>
<button @click='test1("+name+")'>点我</button>`;
console.log(html1)
4、创建对象
// 定义对象
let id=1;
let name="王恒杰";
let age=18;
//5版本封装对象
let student={id:id,name:name,age:age};
console.log(student);
//6版本封装对象
var student2={id,name,age};
console.log(student2)