当前位置: 移动技术网 > IT编程>开发语言>JavaScript > ES6 class -- Class 的基本语法

ES6 class -- Class 的基本语法

2020年03月27日  | 移动技术网IT编程  | 我要评论
类: 降低维护成本、使代码高度复用、扩充方便灵活 OOP 面向对象开发 核心:封装 类->工厂->对象 ES6中的类 //车类 class Car{ //构造函数 constructor(){ console.log("开始造车"); } } //实例化,类->对象 let c=new Car(); ...

类:

降低维护成本、使代码高度复用、扩充方便灵活

 

oop 面向对象开发

核心:封装

类->工厂->对象

 

es6中的类

//车类
class car{
    //构造函数
    constructor(){
        console.log("开始造车");
    }    
}

//实例化,类->对象
let c=new car();

 

 

构造函数的写法有点类似于简洁表示法:

//构造函数的写法类似简洁表示法
let obj={
    //普通写法
    fn:function(){

    },
    //简洁表示法
    fn2(){
        
    }
}

 

//车类
class car{
    //构造函数
    constructor(wheel,color,length,width){//接收参数
        //给属性赋值,this指向当前实例化的结果
        this.wheel=wheel;
        this.color=color;
        this.length=length;
        this.width=width;
        this.speed=0;
    }    

    //方法
    speedup(){
        this.speed+=1;
    }
}

//实例化,类->对象
let c=new car(3,"#abcdef",20,40);
console.log(c);
c.speedup();//调用实例(对象)的方法
console.log(c.speed);//获取实例(对象)的属性

 

 

不同实例之间是相互独立的

//车类
class car{
    //构造函数
    constructor(wheel,color,length,width){//接收参数
        //给属性赋值,this指向当前实例化的结果
        this.wheel=wheel;
        this.color=color;
        this.length=length;
        this.width=width;
        this.speed=0;
    }    

    //方法
    speedup(){
        this.speed+=1;
    }
}

//实例化,类->对象
let c1=new car(3,"#abcdef",20,40);
let c2=new car(4,"pink",10,40);
console.log(c1,c2);

 

 

音乐播放器类实例

<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>es6 class</title>
</head>
<style>

</style>
<body>

<div id="app"></div>

<script>

//模拟一个播放器类
class audioplayer{
    constructor(container){//接收参数
        this.container=document.queryselector(container);
        this.songslist=[];
        this.dom=null;
        this.audio=new audio();
        this.status=0;//标记播放器的状态

        this.getsongs();//获取歌单列表
        this.createelement();//创建dom
        this.bindevent();//绑定事件
        this.render();//渲染到页面
    }

    getsongs(){
        //模拟ajax请求拿数据
        this.songslist=[
            {
                songname:"name1",
                songcover:"cover1",//封面
                songsinger:"singer1",//歌手
                songurl:"url1"//资源地址
            },
            {
                songname:"name2",
                songcover:"cover2",//封面
                songsinger:"singer2",//歌手
                songurl:"url2"//资源地址
            }
        ];
    }

    createelement(){
        const div=document.createelement("div");
        div.innerhtml=`
            <div class="btn">播放按钮</div>
            <div>进度条</div>
        `;
        this.dom=div;
    }

    bindevent(){
        this.dom.queryselector(".btn").addeventlistener("click",()=>{
            console.log("开始播放");
        })
    }

    render(){
        this.container.appendchild(this.dom);
    }
}

new audioplayer("#app");

</script>
</body>
</html>

 

如您对本文有疑问或者有任何想说的,请点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网