This project has moved. For the latest updates, please go here.

changing 'this' global object

Jan 31, 2012 at 9:47 PM


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"



Jan 31, 2012 at 11:31 PM
Edited Jan 31, 2012 at 11:32 PM

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 7: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?