- Home /
Extending from interface in JS?
What is the syntax for creating an interface, an abstract base class, and extending a class from it (In JavaScript)?
Answer by podperson · Oct 31, 2011 at 11:23 AM
Unity JavaScript now (as of 3.4, possibly earlier) supports implements, so the old best answer no longer holds.
Here, as an example, is an implementation of the QCAR ITrackableEventHandler interface in JavaScript.
class TrackableEventHander implements ITrackableEventHandler {
var tracked : boolean;
function OnTrackableStateChanged(
previousStatus : TrackableBehaviour.Status,
newStatus : TrackableBehaviour.Status
){
if( newStatus == TrackableBehaviour.Status.TRACKED ){
tracked = true;
} else {
tracked = false;
}
}
}
does this mean you can use extends and implements in the same class definition? and can you add multiple "implements"?
This page shows how to actually create an interface using the interface keyword. http://docs.unity3d.com/Documentation/$$anonymous$$anual/$$anonymous$$onoUpgradeDetails.html
And, yes, you can use both extends and implements.
Answer by duck · Apr 19, 2010 at 11:52 AM
While Unity's Javascript does support inheritance and interfaces, it has the very limiting caveat that you can either inherit your class from an existing class, or declare one interface. Eg:
// in C# you can declare a combination of inheritance and multiple interfaces: class Apple : MonoBehaviour, ICollectable, IEatable, IThrowable { ... }
// Javascript - only one allowed, eg: class Apple extends BaseObject { ... }
// or: class Apple extends IThrowable { ... }
And as far as I can see, there's no way to actually define an interface in JS - you just have to define the interface in C#, and have it in an earlier compilation pass so that your JS script can see the type.
Answer by Ashkan_gc · Apr 19, 2010 at 09:48 AM
you can not define interfaces in js but you can inherit from them using extend keyword i think you can create abstract classes using abstract keyword but i am not sure because this implementation of unity's js is unity's own implementation and there is not any specification available. i don't know what version of the ECMA script they support. you can just create abstract or virtual methods in you classes in C# or create interfaces n C# and use them in js. if you want to create an OO structure for your program use C# programming language.
You can define them as of Unity 3.5. http://docs.unity3d.com/Documentation/$$anonymous$$anual/$$anonymous$$onoUpgradeDetails.html
Answer by dentedpixel · Aug 01, 2013 at 09:31 PM
You can define an interface in Javascript, here is the syntax:
interface MyInterface{
function someMethod( param:int );
}
then implementing the interface
public class FooSubClass extends MonoBehaviour implements MyInterface{
function someMethod( param:int ){
}
}