Quantcast
Channel: ClearScript
Viewing all articles
Browse latest Browse all 2297

New Post: I can override methods with whatever value on 5.4.4

$
0
0
The following anomaly executes on version 5.4.4. Is this change intentional? If so, is there a way to disable it? Properties are still restricted to their types, only methods not.

public class Calculator
{
    public int Add(int a, int b)
    {
        return a + b;
    }

    public int Sub(int a, int b)
    {
        return Add(a, -b);
    }
}

class Program
{
    static void Main(string[] args)
    {
        using (var engine = new V8ScriptEngine())
        {
            engine.AddHostObject("calc", new Calculator());

            int result = (int)engine.Evaluate("calc.Add(2, 3)");
            // Prints 5
            Console.WriteLine(result);

            // Override the method...
            engine.Execute("calc.Add = 'add is now a string'");
            string newResult = (string)engine.Evaluate("calc.Add");
            // Prints "add is now a string"
            Console.WriteLine(newResult);

            // calc.Sub still works though
            result = (int)engine.Evaluate("calc.Sub(10, 20)");
            // Prints -10
            Console.WriteLine(result);

            // Does not work anymore (throws "Add is not a function")
            result = (int)engine.Evaluate("calc.Add(7, 8)");
        }
    }
}

Viewing all articles
Browse latest Browse all 2297

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>