js-不使用class关键字实现面向对象特性-创建类

'use strict'


//创建people类
const People = (function(){
    //静态私有变量
    let hasCreatedPeopleInstanceNum = 0;

    //People类构造函数 
    const peopleConstractor = function( name, id, gender )
    {
        //私有变量
        let myId = id;
        //私有方法
        let isVip = privateIsVIP;
       
        try{
            //首先检查 这个类有没有创建过多的实例,有的话就不再创建实例(为了节约内存),否则可以创建
            hasCreatedPeopleInstanceNum += 1;
            checkInstanceNum();
            //首先检查形参类型,正确的话直接实例化一个对象,从而保证了程序的正确性
            checkFormalParameter(name, id, gender);

            this.name = name;
            this.id = id;
            this.gender = gender;
            if(isVip(myId))
            {
                this.isVip = true;
            }else{
                this.isVip = false;
            }

        }catch(error){
            console.error(error.message);
            return ;
        }
        //公有方法, 或者叫 特权方法
        this.sayMyName = publicSayMyName;
        this.getMyName = publicGetMyName;
        this.introduceSelf = publicIntroDuceSelf;
    }
    const checkFormalParameter = function(name, id, gender)
    {
        let tag1 = typeof name === 'string';
        let tag2 = typeof id === 'number';
        let tag3 = typeof gender === 'string';
        if(! (tag1 && tag2 && tag3))
        {
            throw new Error('formalParameter wrong! people instance create fail!');
        }
    }
    const publicSayMyName = function()
    {
        console.log(this.name);
    }
    const publicGetMyName = function()
    {
        return this.name;
    }
    const privateIsVIP = function(id)
    {//假设 id 为奇数 的人为 VIP
        return id % 2 === 0 ? false : true;
    }
    const hasCreateTooManyInstance = function()
    {
        return hasCreatedPeopleInstanceNum > 100 ? true : false;
    }
    const checkInstanceNum = function()
    {
        if(hasCreateTooManyInstance())
        {
            throw new Error('create too many instance!');
        }
    }
    const publicIntroDuceSelf = function()
    {
        console.log('name:',
                    this.name,
                    'gender:',
                    this.gender,
                    'isVIP:',
                    this.isVip)
    }
    peopleConstractor.prototype = {
        allGender : ['male', 'female'],
        ancestors : 'monkey'
    }

    return peopleConstractor;
})();


let p1 = new People('anQing', 1, 'male');
let p2 = new People('wangDaChui', 2, 'male');
p1.introduceSelf();
p2.introduceSelf();


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值