- Home /
How can I write and use extension methods in JS?
In C# there are extension methods that can be written such as:
// Create an extension for string public static class MyExtension { public static bool IsCaptialized(this string value) { return Char.IsUpper(value[0]); } }
// And then use it void TestExtension() { string shouldBeCapitalized = "Capitalized"; Debug.Log(shouldBeCapitalized.IsCaptialized()); }
- Can I write extension methods in JS?
- Can I use extension methods written in C# with JS?
Progress update.
As I have been trying some C#/JS since I asked the question, it appears that JS does not recognize the extensions I wrote in C#. I placed the extensions in Standard Assets folder so that it would compile before the JS. That leaves me to think there isn't any way in JS to use extension methods and as such there is no way to write extension methods in JS, at least not for the present.
Answer by Statement · Dec 17, 2010 at 03:58 PM
Since no other answers have been posted and I haven't been able to find any solution through my own fiddling, I draw the conclusion that it's a simple case;
Javascript for Unity3D does not support extension methods.
Same conclusion I came to when I answered the same question two weeks ago
I'm sorry, I didn't notice any other answers here? Or is this a duplicate question?
Not a dupe, but similar. http://answers.unity3d.com/questions/26059/can-i-extend-vector3-using-javascript/26061#26061 . And eep, that wasn't two weeks ago
Answer by amirabiri · Oct 22, 2011 at 05:06 PM
There are no extension methods in JS, or in Unity's version of JS (which isn't traditional JS).
JS won't recognize C# extension methods because C# extension methods are not real artefacts added to the class, they are syntactic sugar. In essence they are just static methods. The C# compiler, as a feature of the language, knows how to "use" them from an object context given the right syntax. But as said - it's just a bit of magic, they are not real. Hence they are not visible as more than static methods from a cross-language point of view.
Generally speaking, if you want a "quick and easy" language to program in, use JS. If you come from a "heavier" computing background and would like to have the full power of a strong mainstream language at your disposal, use C#. For larger projects I'd recommend C#.
Either way don't expect to get the same from both languages, they are different.
Your answer
Follow this Question
Related Questions
Input.GetButtonDown not working at ALL 1 Answer
Reload Level on Collision 4 Answers
C# to Unityscript problem. 1 Answer
How to declare and use a enum variable in Javascript? 2 Answers
Unable to load script, when referencing an extension method 2 Answers