zoukankan      html  css  js  c++  java
  • 《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都指向同一个对象。

    接下来就是第四篇了。。越来越难理解啦...

  • 相关阅读:
    量化投资_期货日内交易几个问题的考证
    量化投资_上一个交易时间段对今日收盘价涨跌的影响
    RunJS
    sublime3快捷 输入html
    NLP学习资源
    Invert Binary Tree
    定时任务 Crontab命令 详解
    根据职位名,自动生成jd
    使用python + tornado 做项目demo演示模板
    Awk 实例
  • 原文地址:https://www.cnblogs.com/luohaoran/p/5954237.html
Copyright © 2011-2022 走看看