changing 'this' global object

Jan 31, 2012 at 10:47 PM

Hi,

I am looking for some help in achieving the following -  I am trying to simulate a browser object model.  I have a window object defined with various properties and functions marked up with JSFunction and JSProperty.  I am trying to "merge" an instance of this object with the global object (this).

e.g the following javascript statements need to be true:

1) window != null
2) this == window
3) this.alert("ABC"); // calls window.alert("abc");
4) window.alert("ABC") // same as above
5) window.innerWidth; // needs to call the innerWidth property
6) this.innerWidth; // needs to be same as above

I was wondering if something like: engine.Global["window"] = engine.Global  - will sort out number 2 for the rest it would be good if I could merge the properties of an existing object with global, I was looking into PopulateFields, and was hoping there might be a way of adding the properites to global, but having them call on my clr instance of "window"

Cheers,

James

Coordinator
Feb 1, 2012 at 12:31 AM
Edited Feb 1, 2012 at 12:32 AM

There are a number of ways to do this, here's the simplest:

engine.Global["window"] = engine.Global;
engine.SetGlobalFunction("alert", new Action(msg => Console.WriteLine(msg)));

You could also create a new object and copy the functions into the global object:

var myObject = new MyObject(engine);
engine.Global["alert"] = myObject["alert"];

 The main issue there is that the instance of the MyObject class wouldn't be able to be hooked up properly since it is being called on the global object.  This can be mitigated by making the methods on the MyObject class static.

If you need it, you can get a reference to the ScriptEngine instance by declaring your methods like so:

[JSFunction(Name = "alert", Flags = JSFunctionFlags.HasEngineParameter)]
public static void Alert(ScriptEngine engine, string message)
{
}
Feb 1, 2012 at 8:27 AM

Hi Thanks for the reply,

I can see the SetGlobalFunction would work with a delegate, but how would this work for properties? e.g getters and setters.  Would another approach be to subclass GlobalObject, add my properties to it, and then overrwrite the Global instance on the engine?

 

Thanks,

James