ES6的常用方法
cont 声明常量(不能被修改)
const a = 12; a = 13; console.log(a); #12
模版字符串(字符串拼接)
var name = ‘周军豪‘,age=21;
var str1 = `他叫${name},年龄${age}岁`;
console.log(str1)
箭头函数
es5写法:
function add(x,y) {
x+y
}
add(1,2)
es6:
#var 函数名 = ()=>{}
var add2 = (a,b)=>{
a+b
}
alert(add2(2,3))
字面量方式创建对象
var person = {
name:‘小明‘,
age:18,
fav:function() {
// alert("抽烟喝酒烫头")
// es5的函数中的this指向了当前对象
alert(this.name)
}
};
person.fav();
#es6
var person2 = {
name:‘小明2‘,
age:18,
fav:()=>{
// es6注意事项:箭头函数会改变this的指向 父级
console.log(this);
}
}
person2.fav(); //Window {postMessage: ?, blur: ?, focus: ?, close: ?, frames: Window, …}
对象的单体模式
使用对象的单体模式解决了this的指向问题
var person2 = {
name:‘小明2‘,
age:18,
fav(){
console.log(this)
}
}
person2.fav() #{name: "zhou", age: 12, fav: ?}
ES6的面向对象
es5的构造函数,创建对象
function Dog(name,age) {
this.name=name;
this.age=age;
}
//set方法
Dog.prototype.showName = function () {
alert(this.name)
};
//示例对象,get方法
var d = new Dog("alex",12);
d.showName()
es6使用class 类方法创建
class Cat{
// constructor 构造器 class方式创建 单体模式之间不要有逗号
constructor(name,age){
this.name = name;
this.age = age;
}
fun(){
alert(this.age)
}
}
var d =new Cat("alex",13);
d.fun()
VUE的使用
vue的设计模式是MVVM
点击更换图片以及下一张示例:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>练习</title>
<style>
.div2{
width: 100px;
height: 100px;
background: green;
}
.div3{
background: yellow;
}
</style>
</head>
<body>
<div id="app">
<span>{{msg}}</span>
<span v-if="show">显示</span>
<span v-if="noshow">消失</span>
<div v-show="noshow">隐藏</div>
<button @click="showHandler">按钮1</button> <!--绑定事件-->
<div class="div2" :class="{div3:isyellow}"></div> <!--绑定属性-->
<button @click="change_yellow">变黄</button>
<a href="" v-bind:href="url">百度</a>
<hr>
<img :src="imgSrc" >
<ul>
<li v-for="(item,index) in imgArr" @click="currentHandler(item)">xxx</li> <!--for循环-->
</ul>
<button @click="next_img">下一张</button>
</div>
<script src="S7-vueDay1/vue.js"></script>
<script>
var app = new Vue({
el:"#app",
data:{
msg:"zhou",
age:12,
show:true,
noshow:false,
isyellow:false,
url:"https:www.baidu.com",
imgSrc:"./S7-vueDay1/images/0.png",
current_index:0,
imgArr:[
‘./S7-vueDay1/images/0.png‘,
‘./S7-vueDay1/images/1.png‘,
‘./S7-vueDay1/images/2.png‘,
‘./S7-vueDay1/images/3.png‘
]
},
methods:{
showHandler(){
this.noshow=!this.noshow
},
change_yellow(){
this.isyellow = !this.isyellow
},
currentHandler(item){
this.imgSrc = item
},
next_img(){
// console.log(this.imgArr.length);
this.current_index = this.current_index+1;
if(this.current_index==this.imgArr.length){
this.current_index = 0
}
this.imgSrc=this.imgArr[this.current_index]
}
}
})
</script>
</body>
</html>