Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Don't override existing prototype functions with extension methods #861

Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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