How to write a function in script# to be called with any object as this, not just with the instance of the class in which it is defined?

混江龙づ霸主 提交于 2019-12-02 00:50:26

This is similar to being able to reference "this" inside a jQuery callback function. See the Current property on jQuery class for example (https://github.com/nikhilk/scriptsharp/blob/cc/src/Libraries/jQuery/jQuery.Core/jQuery.cs).

Specifically, if you write this:

[ScriptImport]
public static class Global {

    [ScriptField, ScriptAlias("this")]
    public static object This {
        get { return null; }
    }
}

Then you can write this:

public static class MyCode {

    public static bool MyFunction() {
         return (Script.GetField<int>(Globals.This, "value") > 100);
    }
}

Of course you could also write the imported class to return a strongly typed class (again see the jQuery example), which would make it possible to write MyFunction without using Script.GetField.

The code above assumes script# 0.8 APIs (which you can get from the project's download page on github). For prior builds replace [ScriptImport] with [Imported] and [ScriptField] with [IntrinsicProperty].

I am hoping to put something like the This property in the Script class so its available out-of-the-box in when 0.8 is finalized.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!