首页 > 代码库 > 《JavaScript设计模式》读书笔记——Day3
《JavaScript设计模式》读书笔记——Day3
一上来写了一个200多行快300行的demo。。结果给我报错,调试半天也没弄好,哎。。
先把这个享元模式说了吧~大概的意思就是说当几个对象之间有相同的动作的时候,一个一个去创建那么必定会造成大量的占据内存,将它们共有的方法提取出来,共享一个对象,这样就节约了内存,提高了响应的速度啦,来,上栗子!
// 享元动作var FlyWeight = { moveX : function ( x ) { this.x = x; }, moveY : function ( y ) { this.y = y; }};// 人物移动方法var Player = function ( x ,y ,c ) { this.x = x; this.y = y; this.color = c;};Player.prototype = FlyWeight;Player.prototype.changeC = function ( c ) { this.color = c;};// 精灵移动方法var Spirit = function ( x ,y ,r ) { this.x = x; this.y = y; this.r = r;};Spirit.prototype = FlyWeight;Spirit.prototype.changeR = function ( r ) { this.r = r;};// 创建人物var player = new Player( 5 , 6 , ‘red‘ );console.log ( player );player.moveX( 6 );player.moveY( 5 );// 创建精灵var spirit = new Spirit( 7 , 5 , 5 );console.log (spirit );spirit.moveX( 6 );spirit.moveY( 5 );spirit.changeR( 5 );
其中人物移动和精灵移动的prototype都指向了FlyWeight这个对象,这就是享元对象的模式,让他们的prototype都指向同一个对象。
接下来就是第四篇了。。越来越难理解啦...
《JavaScript设计模式》读书笔记——Day3
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。