1

I have a few classes (to be precise, there are about 70-100 classes in my project) written in C#. Those classes are converted to Javascript (I have added V8 Javacript MS ClearScript Engine to my project) and integrated in my application. I want to allow my clients to add more functionality to those classes with Javascript rather than c#.

The problem is - I cannot understand how I can add new functions, which would be written in Javascript with ClearScript, to my classes (that were originally written in c#).

I have no idea how I can do it. Is it possible?

C# written search classes method for Javascript:

    [ScriptMember(ScriptMemberFlags.ExposeRuntimeType)]
    public static MdElement GetClass(string mdClass, string mdClassName)
    {
        ...
    }

C# written class MdQuery:

    public class QueryCities : MdQuery {
        // C# methods
        public DataTable GetAll() { ... }
    }

Javascript written extension method:

    function filterByCountry(allCities, countryName) {
        ....
    }

Javascript written use of C# class and Javasctipt extension method:

    var query = Md.GetClass('MdQuery', 'QueryCities');
    var allCities = query.GetAll();
    var resultList = query.filterByCountry(allCities, 'Angola');
    ...
slavayancheg
  • 59
  • 2
  • 12

1 Answers1

1

ClearScript intercepts all property access to host objects, but you can use a Proxy wrapper to add or override whatever you need.

Here's a function that wraps a host object in a proxy:

function extendHostObject(hostObject) {
    let ext = {};
    Object.defineProperty(ext, 'ext', { value: ext, writable: false });
    return new Proxy(hostObject, {
        get: function (target, prop, rec) {
            let value = Reflect.get(ext, prop, rec);
            return (typeof value !== 'undefined') ? value : Reflect.get(target, prop, rec);
        }
    });
}

You can use it like this:

query = extendHostObject(query);
query.ext.filterByCountry = function (allCities, countryName) {
    // TODO: add code here
};
var resultList = query.filterByCountry(query.GetAll(), 'Angola');

Obviously this is just an example and you can customize it any number of ways.

BitCortex
  • 3,328
  • 1
  • 15
  • 19
  • Can I extend C# class with Javascript methods when user call Md.GetClass method, JS methods defined in files, it is possible to call extendHostObject before return host object in C#? – slavayancheg Jun 12 '19 at 06:04
  • 1
    Sure, you can load and execute the JS file so that `extendHostObject` (and any other functions you need) are in place. Then call `ScriptEngine.Current.Script.extendHostObject` from `Md.GetClass`. You'll need to change the return value type to `object`, and you won't need the `ScriptMember` attribute any more. – BitCortex Jun 12 '19 at 11:41