javascript面向对象编程---封装--被动封装+主动封装

封装:把对象内部的数据和操作细节进行隐藏,javascript不支持封装操作,但可以使用闭包函数来模拟类型封装

被动封装:对对象内部数据进行适当约定,这种约定并没有强制性,它主要针对公共对象而言

var Card=function(name,sex,work,detail){//较为安全的公共类

    if(!_checkName(name)) throw new Error('name值非法')

  this.name=name;

  this.sex=_checkSex(sex);

  this.work=_checkWork(work);

  this.detail=_checkDetail(detail)

}

Card.prototype={//类内部的数据检测方法

   _checkName:function(name){},

_checkSex:function(sex){},

_checkWork:function(work){},

_chackDetail:function(detail){},

}

主动封装:函数具有局部作用域,在函数内部声明的变量函数外部无权访问所以真正实现类的封装设计,使用函数是最佳选择

var Card=function(name,sex,work,detail){

   var  _name=name,_sex=sex,_work=work,_detail=detail;

  function _checkName(_name){}

 function _checkSex(_sex){}

 function _checkWork(_work){}

function _checkDetail(_detail){}

this.checkName=function(){return _checkName}//可返回私有方法,供外部不调用

if(!_checkName(_name))  throw new Error('name值非法')

else{

    this.name=_name;

}

this.sex=_checkSex(_sex);

this.work=_checkWork(_work);

this.detail=_checkDetail(_detail);

}

Card.prototype={//公共方法

}

通过特权函数(公共方法)访问私有变量

var Card=funciton(){

   var _name=1;

  function _checkName(){ return  _name;}

 this.checkNmae=funciton(){return _name;}//公共方法访问私有属性

}

function F(){//子类,类继承方法继承

   Card.call(this);

  this.name=_name;//访问超类中的私有属性 ,抛出解析错误

}

var a=new F();

alert(a.name);

alert(a._checkName());//无法访问,解析错误

alert(a.checkName());//访问超类公共方法,间接访问私有属性

猜你喜欢

转载自blog.csdn.net/wenmin1987/article/details/82827933