修改可变对象的方法?

时间:2017-06-15 17:28:38

标签: javascript functional-programming pixi.js ramda.js

鉴于函数式编程在尽可能多地坚持不可变变量时是最好的,并且Ramda总是生成浅层副本,必须的对象如何在一个纯粹的功能框架中处理? ?

例如,考虑PIXI.Sprite(在pixi.js中)。显示系统具有固有的层次结构,它连接在一起并有自己的跟踪对象的方式,因此它可以重复使用纹理等。垃圾收集它们可能是一个真正的问题。

可以采取哪种方法来解决这个问题(以及类似钠类型的强大frp系统)?

具体来说,可以改进这种方法:

  1. 使用某种unsafePerformIO()函数来修改重物。这些对象的所有修改只能通过该功能完成。

  2. 轻量级元信息对象带有所有逻辑。

  3. 这些轻量级信息对象直接引用重物

  4. 下面是Typescript中的完整代码示例,用于演示它的运行情况(只需要导入PIXI和Ramda)。关键行在gameLoop()中:

    let app = new PIXI.Application(window.innerWidth, window.innerHeight);
    document.body.appendChild(app.view);
    
    
    let ball = new PIXI.Graphics();
    ball.beginFill(0xFF0000);
    ball.drawCircle(0,0,40);
    ball.endFill();
    
    ball.y = app.stage.height/2;
    
    app.stage.addChild(ball); //app
    
    let ticker = new PIXI.ticker.Ticker();
    ticker.add(gameLoop);
    ticker.start();
    
    let ballReference = {
        ptr: ball,
        x: 0
    }
    
    function performUnsafeIO(reference) {
        reference.ptr.x = reference.x;
    }
    function gameLoop(deltaTime:number) {
        //this version breaks!
        //ball = R.assoc('x', ball.position.x + deltaTime * 1, ball);
    
        //This works fine... but are there any gotchas?
        ballReference = R.assoc('x', ballReference.x + deltaTime * 1, ballReference);
        performUnsafeIO(ballReference);
    }
    

    (请注意,通过Google发现的此对话是一个很好的参考点:https://web.archive.org/web/20100410001213/http://itmmetelko.com/blog/2008/02/23/functional-programming-immutable-objects-explained-irc-style/

0 个答案:

没有答案
相关问题