js封装
emer 发布于 2019-3-22 16:12 1871 次阅读
/
2、闭包的封装方式,在这个封装方法中,所有的实例成员都共享属性和方法
使得所有得方法和属性都私有且对象间共享
/
var Person=(function(){
/共享函数*/
let checkNo=function(no){
if(!no.constructor=="string"||no.length!=4){
throw new Error("必须为4位数");
};
};
let times=0;//共享数据
return function(no,name,age){
console.log(times++);
this.setNo=function(no){
checkNo(no);
this._no=no;
};
this.getNo=function(){
return this._no;
};
this.setName=function(name){
this._name=name;
};
this.getName=function(){
return this._name;
};
this.setAge=function(age){
this._age=age;
};
this.getAge=function(age){
return this._age;
};
this.setNo(no);
this.setAge(age);
this.setName(name);
}
})();
Person.prototype={
constructor:Person,
toString:function(){
return "no = " + this._no + " , name = " + this._name + " , age = " + this._age;
}
}
let per=new Person("0001",15,"simu");//输出之后times会逐渐增加,变为1、2、3
let per1=new Person("0002",15,"simu1");
let per2=new Person("0003",15,"simu2");
console.log( per.toString());
console.log( per1.toString());
console.log( per2.toString());
jq方式:
var Person=(function(window){ var Person=function(data){ return new Person.fn.init(data); } Person.fn=Person.prototype={ constructor:Person, data1:{ val:12 }, init:function(data){ this.data=data; this.sayHello=function(){ console.log(this.data+"say Hello"); } }, sayHi:function(){ console.log(this.data); console.log(this.data1); }, }; Person.fn.init.prototype=Person.fn; return Person; })(); var p1=Person("lining"); p1.sayHello(); p1.sayHi();