'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();
js-不使用class关键字实现面向对象特性-创建类
最新推荐文章于 2021-11-23 17:22:23 发布