-->

如何写脚本#函数与任何对象,因为这被调用,而不只是在它被定义的类的实例?(How to write

2019-08-02 02:27发布

我在剧本#编写JavaScript。 我想编写一个看起来像一个功能

function myFunc()
{
    if(this.value > 100)
          return true;
    else
          return false;
}

此功能可与具有属性“价值”的任何实例调用。

我怎么能写脚本#这个功能呢? 在脚本#,生成的javascript代码似乎是使本地参考这个当一些其他的对象是作为“这个”传递不起作用。

Answer 1:

这类似于能够引用“这个” jQuery的回调函数内。 例如见(https://github.com/nikhilk/scriptsharp/blob/cc/src/Libraries/jQuery/jQuery.Core/jQuery.cs)jQuery的类Current属性。

特别是,如果你这样写:

[ScriptImport]
public static class Global {

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

然后,你可以这样写:

public static class MyCode {

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

当然,你也可以写导入的类返回一个强类型类(再参照jQuery的例子),这将使得有可能写的MyFunction不使用Script.GetField。

上面的代码假定脚本#0.8的API(你可以从github上项目的下载页面获得)。 事先建立替换[进口]和[ScriptField]与[IntrinsicProperty] [ScriptImport]。

我希望把类似的这个属性的脚本类,所以它可以在0.8敲定外的开箱英寸



文章来源: 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?
标签: script#