CLASS创造类的语法


一、基于ES6中的CLASS重构下面的代码

function ModalFun(x,y){
    // 构造函数体:给实例设置私有属性方法
    this.x=x;
    this.y=y;
}
// 在构造函数原型上设置实例可调用公共属性方法  实例。xxx
ModalFun.prototype.z=10;
ModalFun.prototype.getX=function(){
    console.log(this.x);
}
ModalFun.prototype.getY=function(){
    console.log(this.y);
}
//把其当做普通函数对象、设置静态私有方法
ModalFun.n=200;
ModalFun.setNumber=function(n){
    this.n=n;
};
let m = new ModalFun(10,20);
console.dir(m)
console.dir(ModalFun)

在这里插入图片描述

class Modal{
    //构造函数体
    constructor(x,y){
        this.x = x
        this.y = y
    }
    //给当前实例设置私有的属性和方法
    z=10
    getX = ()=>{}
    //向原型拓展方法
    /*
    *  不能拓展共有属性、增加方法不能是箭头函数【因为语法只能按照下述方法写】
       增加的方法没有prototype属性
       这些方法是不仅可枚举的
       我们可以在外面基于Model.prototype.xxx去弥补上述出现的情况
    */
    getX(){
        console.log(this.x)
    }
    getY(){
        console.log(this.y)
    }
   /*
     设置静态属性和方法
   */
    static o =8
    static setMumber(){
        this.o =90
    }
}
//我们可以在外面基于Model.prototype.xxx去弥补上述出现的情况
Modal.prototype.p=1
// Modal() //5.js:28 Uncaught TypeError: Class constructor Modal cannot be invoked without 'new'  基于class创建的构造函数,只能带new执行,也就是构造函数的方式去执行,不能当做普通函数执行
let m = new Modal(10,20);
console.dir(m)
console.dir(Modal.setMumber())
console.dir(Modal)

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值