简体   繁体   English

更改haxe对象的“ this”范围。 可能?

[英]Changing the “this” scope of a haxe object. Possible?

Is it possible to change the "this" scope of an object, from the outside, very much like in javascript? 是否有可能像在javascript中那样从外部更改对象的“ this”范围?

I see an interesting application, where one could create a container object, having multiple components, where every time a component modifies a property on its own, it actually implicitly modifies a property on the container. 我看到了一个有趣的应用程序,其中一个应用程序可以创建一个包含多个组件的容器对象,每当一个组件自己修改属性时,它实际上隐式地修改了容器上的属性。

Do not get me wrong. 别弄错我的意思。 I know that the same effect can be achieved with events, bindings, observers, and what not. 我知道,事件,绑定,观察者可以实现相同的效果,而其他情况则不能。 Possibilities are indeed endless. 可能性确实是无止境的。 I am just curious about this funky way of delegation. 我只是对这种时髦的授权方式感到好奇。

You can achieve that using Reflect.callMethod , but you must know that it won't be type-safe at compile-time. 您可以使用Reflect.callMethod来实现,但是必须知道,在编译时它不是类型安全的。 Here is a little example : 这是一个小例子:

class Test
{
    public var a:Int;

    public function new()
    {
        this.a = 0;
    }
}

class Test2
{
    public var a:Int;

    public function new()
    {
        this.a = 0;
    }

    public function increment()
    {
        this.a++;
    }

    static public function main()
    {
        var t = new Test2();
        var t2 = new Test();
        Reflect.callMethod(t2, Reflect.field(t, "increment"), []);

        trace(t2.a); //Traces 1
    }
}

Another possible way would be to use macros to rebuild your code for using some another object instead of this. 另一种可能的方法是使用宏来重建代码,以使用其他对象代替它。 However, it would be relatively hard and IMO pointless. 但是,这将相对困难并且IMO毫无意义。 I don't really understand your idea, but basing what I understood from your description, I'd recommend you to look into inline getters and setters on components which would also modify container. 我不太了解您的想法,但是根据您的描述,我建议您研究也会修改容器的组件上的内联getter和setter。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM