Skip to content

Commit

Permalink
Don't override existing prototype functions with extension methods (#861
Browse files Browse the repository at this point in the history
)
  • Loading branch information
lahma committed Apr 9, 2021
1 parent c117961 commit ca10397
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 3 deletions.
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using System.Dynamic;
using System;
using System.Dynamic;
using System.Linq;
using Newtonsoft.Json;

Expand All @@ -20,5 +21,10 @@ public static ExpandoObject DeserializeObject(this string json)
{
return DeserializeObject<ExpandoObject>(json);
}

public static string[] Split(this string value, string split, StringSplitOptions options)
{
return Array.Empty<string>();
}
}
}
12 changes: 12 additions & 0 deletions Jint.Tests/Runtime/ExtensionMethods/ExtensionMethodsTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -57,5 +57,17 @@ public void ShouldPrioritizingNonGenericMethod()

Assert.Equal("Mickey", result.name);
}

[Fact]
public void PrototypeFunctionsShouldNotBeOverridden()
{
var engine = new Engine(opts =>
{
opts.AddExtensionMethods(typeof(CustomStringExtensions));
});
var arr = engine.Execute("'yes,no'.split(',')").GetCompletionValue().AsArray();
Assert.Equal("yes", arr[0]);
Assert.Equal("no", arr[1]);
}
}
}
12 changes: 10 additions & 2 deletions Jint/Options.cs
Original file line number Diff line number Diff line change
Expand Up @@ -118,10 +118,18 @@ private void AttachExtensionMethodsToPrototype(Engine engine, ObjectInstance pro
var descriptor = new PropertyDescriptor(functionInstance, PropertyFlag.None);

// make sure we register both lower case and upper case
prototype.SetOwnProperty(overloads.Key, descriptor);
JsValue key = overloads.Key;
if (!prototype.HasOwnProperty(key))
{
prototype.SetOwnProperty(key, descriptor);
}
if (char.IsUpper(overloads.Key[0]))
{
prototype.SetOwnProperty(char.ToLower(overloads.Key[0]) + overloads.Key.Substring(1), descriptor);
key = char.ToLower(overloads.Key[0]) + overloads.Key.Substring(1);
if (!prototype.HasOwnProperty(key))
{
prototype.SetOwnProperty(key, descriptor);
}
}
}
}
Expand Down

0 comments on commit ca10397

Please sign in to comment.