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

redefining toString() - don't know what to expect

Nov 21, 2014 at 2:45 PM
One of my users created a toString() function which miserably failed, always returning [object Undefined].

I created a test, and the unexpected behaviour seems to be triggered by using GlobalMembers.

I do not know exactly what behaviour to expect in the context of clearscript, but the function toString cannot be redefined once the global host object is added.
Is it a bug, is it a design feature ?

Here is the test code :
        class foo
        {
            public string A { get; set; }
        }

        [Test]
        public virtual void Test_ToString_v8_base()
        {
            using(var run = new V8ScriptEngine())
            {
                var tsBefore = run.Evaluate("toString()");
                Assert.AreEqual("[object Undefined]", tsBefore);// is it ok ?

                run.Execute(@"function toString(){return 'AAA';}");
                var tsBefore2 = run.Evaluate("toString()");
                Assert.AreEqual("AAA", tsBefore2);

                var foo = new foo();
                run.AddHostObject("foo", HostItemFlags.GlobalMembers, foo);

                var tsAfter = run.Evaluate("toString()");

                run.Execute(@"function toString(){return 'BBB';}");

                var tsAfter2 = run.Evaluate("toString()");
                Assert.AreEqual("BBB", tsAfter2);// NOK: it is still [object Undefined]
                Assert.AreEqual("AAA", tsAfter); // don't know what to expect here..
            }
        }
Coordinator
Nov 24, 2014 at 12:32 PM
Hi Julien,

In the test code above, the initial toString() call does not involve ClearScript at all. The "[object Undefined]" result makes sense; the script engine finds the built-in function on the global object's prototype chain, and invokes it with an undefined this binding. Note that the result is different if you bind this to the global object via this.toString().

The result of the second call is also expected; V8 invokes the user-defined function that now hangs off the global object.

The result of the third call is due to a ClearScript bug. The GlobalMembers feature incorrectly exposes the proxy's built-in toString() method as a global member that overrides the user-defined function. We're testing a fix and will post it very soon.

Thanks bringing another ClearScript issue to our attention!
Coordinator
Nov 26, 2014 at 11:33 AM
Fix posted here.