几年前曾经看过一遍设计模式,但是并没有深入学习,现在重新学习一遍。
封装:
首先要明白,封装一个类,这个类都有哪些部分构成
1:构造函数内的,供实例化对象复制用。
2:构造函数外的,直接通过 点语法添加的, 只供该类使用。实例化对象访问不到。(静态公有属性、fan)
3:类的原型中的,也就是prototype 生成的方法。实例化对象可以访问的。
创建一个类:
// 部分1 ,每个实例化对象都有自己的存储空间,互不影响
var Book = function (id , bookname, price) {
//私有属性,方法 ---------------外部不可访问
var id = id,
name = "";
function coutId(){
return id;
}
//公有属性,方法 ---------------外部可访问
this.price = price;
this.copy = function () {
};
// 特权方法,可以访问对象 私有 公有 ---------------外部可访问
this.getName = function () {
return name;
};
this.setName = function ( _name) {
name = _name;
};
this.getId = coutId()
// 构造器
this.setName( bookname );
};
// 部分3
Book.prototype.display = function () {
};
//或者这么写
Book.prototype = {
publicVal : "公有属性对象可访问",
publicFun: function () {
console.log( "公有方法,对象可访问" );
}
};
// 部分2
Book.staticPublicVal = "静态公有属性,实例化对象不能访问";
Book.staticPublicFun = function () {
console.log("静态公有方法,实例化对象不能访问");
};
var book = new Book( "1","js 设计模式" , "99" );
console.log( book.getId );
console.log( book.getName() );
book.setName("张晓锋设计模式"); // 通过特权方法改变私有变量的值
console.log( book.getName() );
console.log( book.staticPublicVal ); //undefined
console.log( Book.staticPublicVal ); // "静态公有属性,实例化对象不能访问";
闭包实现:
var Book = (function () {
// 静态私有变量 ,实例化对象中的该变量均指向统一内存空间
var bookNum = 0;
// 静态私有方法
function checkBook( name ){}
// 创建类
function _book( newId, newName , newPrice ){
// 私有变量
var name, price;
// 私有方法
function checkId( id ){};
// 特权方法
this.getName = function () {
return name;
};
this.setName = function ( _name) {
name = _name;
};
this.getPrice = function () {
return price;
};
this.setPrice = function ( _price ) {
price = _price;
};
// 公有属性
this.id = newId;
// 公有方法
this.copy = function(){};
// 构造器
this.setName( newName );
this.setPrice( newPrice );
bookNum++;
if( bookNum >100 ){
throw new Error("静态私有变量超过100,实例化对象数目过多");
}else{
console.log( "实例化对象个数: "+bookNum );
}
}
// 构建原型
_book.prototype = {
publicVal : "公有属性对象可访问",
publicFun: function () {
console.log( "公有方法,对象可访问" );
}
};
// 返回类
return _book;
})();
var b1 = new Book( "1","js 设计模式" , "99" );
var b2 = new Book( "1","js 设计模式" , "99" );