面向对象编程
1.创建,使用函数
var CheckObject = {
checkName : function() {}
}
创建,使用类(原型,链式)
var CheckObject = function() {
this.checkName = fucntion(){}
}
var a = new CheckObject();
a.checkName();
var CheckObject = function(){};
CheckObject.prototype = {
checkName:function(){}
}
var a = new CheckObject();
a.checkName();
var CheckObject = function(){};
CheckObject.prototype = {
checkName:function(){
return this;
}
}
var a = new CheckObject();
a.checkName();
Function.prototype.addMethod = function(name,fn){
this[name] = fn;
}
var CheckObject = new Function();
CheckObject.addMethod('checkName',function(){});
CheckObject.checkName();
Function.prototype.addMethod = function(name,fn){
this[name] = fn;
return this;
}
var CheckObject = new Function();
CheckObject.addMethod('checkName',function(){});
CheckObject.checkName();
Function.prototype.addMethod = function(name,fn){
this[name] = fn;
return this;
}
var CheckObject = new Function();
CheckObject.addMethod('checkName',function(){
return this;
});
CheckObject.checkName();
Function.prototype.addMethod = function(name,fn){
this.ptototype[name] = fn;
return this;
}
var CheckObject = new Function();
CheckObject.addMethod('checkName',function(){
return this;
});
var a = new CheckObject();
a.checkName();
2.私有属性方法
公有属性方法(特权方法,构造器) this.
类静态私有属性方法
类静态公有属性方法 prototype.
var Book = function(){
var name=1;//私有
this.getName = function(){};//公有,特权,构造器
}
Book.bookNum = 0;//静态私有
Book.prototype = {
isJSBook : false//静态公有
}
var Book = (function(){
var bookNum = 0; //静态私有
function _book(){
var name; //私有
this.getName = function(){}; //公有,特权,构造器
}
_book.prototype = {
isJSBook :false // 静态公有
}
return _book;
})();
继承
//类式继承
function SuperClass(){}
SuperClass.prototype.get = function(){};
function SubClass(){}
SubClass.prototype = new SuperClass();
SubClass.prototype.getSub = function(){};
var a = new SubClass();
a.get();
a.getSub();
//构造函数式继承
function SuperClass(){}
SuperClass.prototype.show(){};
function SubClass(){
SuperClass.call(this);
}
var a= new SubClass();
a.show();// 错误用法
//组合式继承
function SuperClass(){}
SuperClass.prototype,get=function(){};
function SubClass(){
SuperClass.call(this)
}
SubClass.protorype = new SuperClass();
SubClass.prototype.getSub = function(){};
var a = new SubClass();
a.get();
a.getSub();
//原型式继承
function inheritObject(o){
function F(){}
F.prototype = o;
return new F();
}
var book = {};
var newBook = inheritObject(book);
newBook.xxx;
//寄生式继承
function createBook(obj){
var o = new inheritObject(obj);
o.get = function(){};
return o;
}
var book = {};
var newBook = createBook(book);
newBook.xxx;
//寄生组合式继承
function inheritPrototype(subClass,superClass){
var p = inheritObject(superClass.prototype);
p.constructor = subClass;
subClass.prototype = p;
}
var SuperClass= {};
SuperClass.prototype.get= fucntion(){};
var SubClass(){
SuperClass.call(this);
};
inheritPrototype(SubClass,SuperClass);
SubClass.prototype.getSub = fucntion(){};
var a= new SubClass();
a.xxx;
创建型设计模式:处理对象创建
3.简单工厂模式
//先定义类,然后用函数返回一个类的实例对象
var PopFactory = function(name){
switch(name){
case 'alert':return newLoginAlert();
}
}
var userNameAlert=PopFactory ('alert');
//用函数返回一个对象
function createPop(type,text){
var o=new Object();
o.content = type;
o.show = function(){};
if(type === 'alert'){}
return o;
}
var userNameAlert = createPop('alert','xxx');
4.工厂方法模式
//在函数的属性里定义类,然后用函数返回一个类的实例对象
var Factory = function(type,content){
if(this instanceof Factory){
var s= new this[type](content);
return s;
}else{
return new Factory(type,content);
}
}
Factory.prototype={
Java:fucntion(){}
}
5.抽象工厂模式
//在函数的属性里定义抽象类,然后用函数返回一个抽象类的子类,然后用子类创建实例对象
var VeicleFactory = function(subType,superType){
if(typeof VehicleFactory[superType] === 'function'){
function F(){};
F.prototype = new VehicleFactory[superType]();
subType.constructor = subType;
subType.prototype = new F();
}else{
throw new Error('未创建该抽象类');
}
}
VhicleFactory.Car = function(){
this.type ='car';
}
VhicleFactory.Car.prototype = {
getPrice:function(){}
}
var BMW = function(price){
this.price =price;
}
VhicleFactory(BMW,'Car');
BMW.prototype.getPrice = function(){
return this.price;
}
var car = new BMW(1000);
car.getPrice();
car.type;
6.建造者模式
//用函数返回一个实例化对象,该实例化对象的某些属性是其他类的实例对象
var Human = fucntion(){};
Human.prototype={};
var Name = fucntion(name){};
var Work = function(work){};
Work.prototype=fucntion(){};
var Person = function(name,work){
var _person = new Human();
_person.name = new Name(name);
_person.work =new Work(work);
return _person;
}
var person = new Person('xxx','xxx');
7.原型模式
//先创建父类,再创建子类,最后通过子类创建实例对象
var LoopImages=function(){};
LoopImages.prototype={};
var FadeLoopImg = function(){
LoopImages.call(this);
}FadeLoopImg.prototype = new LoopImages();
var fadeImg = new FadeLoopImg();
//原型继承,创建一个对象,该对象的原型复制其他属性
var prototypeExtend(){
var F = function(),args=arguments,i=0,len=args.length;
for(;i
for(var j in args[i]){
F.prototype[j]=args[i][j];
}
}
return new F();
}
var penguin = prototypeExtend({xxx});
penguin.xxx;
8.单例模式
//用对象收编函数,此对象相当于命名空间
//单例模式还可以用来创建小型代码库,静态变量,惰性单例
var Ming = {
g:function(){}
}
结构型设计模式:如何将类或对象组合成更大更复杂的结构
9.外观模式
//兼容处理
function addEvent(dom,type,fn){
if(dom.addEventListener){
dom.addEventListener(type,fn,false);
}else if(dom.attachEvent){
dom.attachEvent('on'+type,fn);
}else{
dom['on'+type]=fn;
}
}
addEvent(xxx,'click',function(){});
10.适配器模式
//把旧框架的方法用新框架重写
A.g=function(id){
return $(id).get(0);
}
//适配多个参数
function doSomeThing(obj){
var _adapter = {
name:'xxx'
}
for(var i in _adapter){
_adapter[i] = obj[i] || _adapter[i];
}
}
//数据适配
var arr = ['js','book','前端','8月1日'];
function arrToObjAdapter(arr){
return{
name:arr[0],
type:arr[1],
title:arr[2],
data:arr[3]
}
}
var arrToObjAdapter(arr);
//服务器端数据适配
function ajaxAdapter(data){
return [data[key1],data[key2]]
}
11.代理模式
//统计代理
car Count = (fucntion(){
var _img = new Image();
return function(param){
var str = 'http://www.count.com/a.gif?';
for(var i in param){
str+=i+'='+param[i];
}
_img.src = src
}
})()
Count({num:10})
//jsonp
function jsonpCallBack(res,rep){}
$data = $_GET['data'];
$callback = $GET['callback'];
echo $callback."('success','".$data."')";
?>
12.装饰者模式
var decorator = function(input,fn){
var input = document.getElementById(input);
if(typeof input.onclick === 'function'){
var oldClickFn = input.onclick;
input.onclick = function(){
olc=dClickFn;
fn();
}
}else{
input.onclick = fn;
}
}
13.桥接模式
//分离事件与UI
fucntion changeColor(dom,color){
dom.style.color = color;
}
var spans = document.getElementByTagName('span');
spans[0].onMouseover = function(){
changeColor(this,'red');
}
14.组合模式
//抽象类
var News = function(){
this.children = [];
this.element = null;
}
New.prototype = {
init:function(){
throw new Error(‘请重写你的方法’);
}
}
//类簇1
var Container = function(id,parent){
New.call(this);
this.id = id;
this.init();
}
inhertPrototype(Container,News);
Container.prototype.init = function(){}
//类簇2
var ImageNews= function(clasname){
New.call(this);
this.init();
}
inhertPrototype(ImageNews,News);
ImageNews.prototype.init=function(){}
//实例对象
var news1 = new Container('news');
news1.add(
new Item('normal').add(
new ImageNews('xxx')
)
)
15.享元模式
//翻页时改变dom内容
var FlyWeight = function(){
var created = [];
function(){
var dom = document.createElement('div');
document.getElementById('container').appendChild(dom);
created.push(dom);
return dom;
}
return{
getDiv:function(){
if(created.length <5){
return create();
}else{
var div = created.shift();
created.push(div);
return div;
}
}
}
}
行为型设计模式:不同对象之间职责划分或算法抽象
16.模板方法模式
//父类
var Alert = function(){}
Alert.prototype={}
//子类
var RightAlert = function(){
Alert.call(this);
}
RightAlert.prototype = new Alert();
new RightAlert().init();
17.观察者模式
var Observer = (function(){
var _message={};
return {
regist:function(type,fn){
if(typeof _messages[type] === 'undefined'){
_messages[type] = [fn];
}else{
_messages[type].push(
}
},
fire:function(){
if(!_messages[type])
return;
var events = {
type:type,
args:args||{}
},
i=0,
len = _messages[type].length;
for(;i
_messages[type][i].call(this,events);
}
},
remove:function(){
if(_meassages[type] instanceof Array){
var i = _messages[type].length -1;
for(;i>=0;i--){
_messages[type][i] ===fn && _messsages[type].splice(i,1);
}
}
}
}
})();
var Student = function(result){
var that = this;
that.say = function(){}
};
Student.prototype.answer = function(question){
Observer.register(question,this,say);
}
Student.prototype.sleep = function(){
Observer.remove(question,this.say);
}
var Teacher = function(){};
Teacher.prototype.ask=function(){
Obeserve.fire(question);
}
var student1 = new Student(),student1 = new Student(),student1 = new Student();
student1.answer('问题1');
student1.answer('问题2');
student2.answer('问题1');
student3.answer('问题1');
student3.answer('问题2');
student1.sleep('问题2');
var teacher = new Teacher();
teacher.ask('问题1');
teacher.ask('问题2');
18.状态模式
var ResultState = function(){
var States = {
state0:function(){}
}
function show(result){
States['state'+result]&&State['state'+result]();
}
return {
show:show
}
}
19.策略模式
var PriceStrategy = function(){
var stragtery = {
return30:function(price){}
}
return function(algorithm,price){
return stragtegy[algorithm]&&stragtegy[algorithm](price);
}
}();
var price=PriceStrategy('return30','312');
20.职责链模式
请求模块,响应数据适配模块,创建组件模块单元测试
21.命令模式
var viewCommand = (function(){
//模板类型
var tpl={
product:[
'
{#text#}
'].join(''),
title:[].join()
},
html = '';
function formateString(str,obj){
return str.replace(/\{#(\w+)#\}/g),function(match,key){
return obj[key];
})
}
var Action = {
create:function(data,view){
if(data.length){
for(var i =0,len=data.length;i
html+=formateString(tpl[view],data[i]);
}else{
html+=formatString(tpl[view],data);
}
}
},
display:function(container,data,view){
if(data){
this.create(data,view);
}
document.getElementById(container).innerHTML = html;
html='';
}
}
return function excute(){
msg.param = Object.prototype.toString.call(msg.param) === "[objectArray]"?msg.param:[msg.param];
Action[msg.command].apply(Action,msg.param);
}
})();
viewCommand({command:'display',param:{'title',titleData,'title'}});
22.访问者模式
function bindIEEvent(dom,type,fn,data){
var data =data||{};
dom.attachEvent('on'+type,function(e){
fn.call(dom,e,data);
})
}
23.中介者模式
var mediator = function(){
var _msg = {};
return {
register:function(type,action){
if(!_msg[type]){
_msg[type] = {};
}
_msg[type].push(action);
},
send:function(){
if(_msg[type]){
for(var i=0,len=_msg[type].length;i
_msg[type][i]&&_msg[type][i]();
}
}
}
}
}();
24.备忘录模式
var Page = function(){
var cache ={};
return function(page,fn){
if(!cache[page]){
$.post('xxx',{page:page},function(res){
if(res.errNo == 0){
cache[page] = res.data;
}
showPage(page,res.data);
fn&&fn();
})
}
}
}
25.迭代器模式
var Iterator = function(items,container){
var container = container && document.getElementsByTagName(container) || document;
items = container.getElementsByTagName(items),
length = items.length,
index = 0,
splice = [].splice;
return{
first:function(){
index = 0;
rerurn items[index];
},
second:fucntion(){
index = items.length -1;
rerurn items[index];
},
pre:fucntion(){
if(--index >0){
return items[index]
}else{
index = 0;
rerurn null;
}
},
next:function(){
if(++index > length){
return items[index];
}else{
index = length -1;
return null;
}
},
get:function(num){
index = num >=0?num%length:num%length +length;
rerurn items[index];
},
dealEach:function(fn){
var args = splice.call(arguments,1);
for(var i=0;i
fn.apply(items[i],args);
}
},
dealItem:fucntion(num,fn){
fn.apply(this.get(num),splice.call(arguments,2));
},
exclusive:function(num,allFn,numFn){
this.dealEach(allFn);
if(Object.prototype.toString.call(num) === "[Object Array]"){
for(var i=0,len = num.length;i
this.getItem(num[i],numFn);
}
}else{
this.getItem(num[i],numFn);
}
}
}
}
//数组迭代器,对象迭代器
//同步变量迭代取值器
var AGetter = function(key){
if(!A){
return undefined;
}
var result = A;
key = key.split(.);
for(var i = 0;,len=key.length;i
if(result[key[i]] !== undefined){
result = result[key[i]]
}else{
return undefined;
}
}
return result;
}
//同步变量迭代赋值器
var Asetter = function(key,val){
if(!A)
return false;
var result = A;
key = key.split('.');
for(var i =0,len=key.length;i
if(result[key[i]] === undefined){
result[key[i]] = {};
}
if(!(resultp[key[i]] instanceof Object)){
throw new Error('A.'+key.splice(0,i+1).join('.')+'is not Object');
return false;
}
return result[key[i]];
}
return result[key[i]]= val;
}
// 分支循环嵌套问题
function dealImage(){
var Deal = function(){
var method = {
'red':function(){}
}
return function(type){
return method[type];
}();
function eachData(fn){
for(var i=0,len=data.length;i
fn(i);
}
}
}
}
26.解释器模式
算法