UnityScript versus JavaScript
(→Privacy) |
Isaiah Kelly (Talk | contribs) (rewrote part of the introduction and added UnityScript notice) |
||
(46 intermediate revisions by 5 users not shown) | |||
Line 1: | Line 1: | ||
− | + | {{UnityScript Notice}} | |
− | JavaScript has no classes. This is because it's a prototypal language, and not a classical one. Inheritance happens with [more dynamic] objects, rather than [unchanging] classes. | + | '''Note:''' This page attempts to explain the differences between JavaScript (ECMAScript) and UnityScript as succinctly and clearly as possible. If you have any suggestions, feel free to add them to the author's [[User_talk:Ppeterson|talk page]]. |
− | <javascript>function Machine(x) { | + | |
+ | == Overview == | ||
+ | |||
+ | === Terminology === | ||
+ | |||
+ | It is not uncommon for Unity developers and even members of Unity Technologies to refer to Unity's JavaScript like language as simply "JavaScript", as if it was equivalent or interchangeable with what most people know of as JavaScript on the web. However, the two are actually very different languages. Although they do resemble each other syntactically they have very different semantics. While "JavaScript" is merely a generic name and could refer to any one of many implementations of the ECMAScript specification, Unity's "JavaScript" language doesn't even come close to conforming to that specification — nor does it try to. It's a proprietary language and it doesn't actually follow any concrete specification of standard JavaScript and is modified at will by the engine developers. | ||
+ | |||
+ | Because of this, the vast majority of JavaScript libraries you find will not work by default in Unity. Unity's "JavaScript" is most similar to Microsoft's JScript.NET, although it is not quite identical. Thus many developers prefer to call the language Unity uses "UnityScript" instead, to help differentiate it. Some people consider this to be "just semantics", but when people call both "JavaScript" it becomes a lot harder to search the nternet for solutions and help related to Unity. It's also quite a lot of trouble to continuously specify whether one is referring to "real" JavaScript or Unity's version. So it's best to just stick with "JavaScript" for real JavaScript and "UnityScript" for Unity's language. | ||
+ | |||
+ | === JavaScript is class-free === | ||
+ | |||
+ | JavaScript (i.e. the language that's not UnityScript) has no classes. This is because it's a prototypal language, and not a classical one. Inheritance happens with [more dynamic] objects, rather than [unchanging] classes, in JavaScript. | ||
+ | <syntaxhighlight lang="javascript">function Machine(x) { | ||
this.kind = ["bulldozer", "lathe", "car"][x]; | this.kind = ["bulldozer", "lathe", "car"][x]; | ||
} | } | ||
Line 14: | Line 26: | ||
print(typeof c.announce); // "function" | print(typeof c.announce); // "function" | ||
− | c.announce();</ | + | c.announce(); // prints "I am a car."</syntaxhighlight> |
− | + | As shown above, in JavaScript, a function can create an object, when called with the <code>new</code> keyword. After that happens, the prototype (template) object Machine can be extended to provide additional functionality, and all class instances, past and future, are affected by this extension. | |
− | < | + | |
− | class | + | |
− | + | UnityScript has classes, unlike JavaScript. Also, in UnityScript, once you've defined a class, that class is more or less fixed for the duration of the runtime of your program. (N.B. There may be some exceptions to this rule, such as Reflection, but you probably do not need this and should not be using it because it's not very efficient.) However, the class system has the added benefit of being an easier-to-read, more familiar (to most) language. | |
− | + | <!--<unityscript--><syntaxhighlight lang="javascript">class Machine { | |
− | <javascript>var | + | var kind : String; // fields are public by default |
− | x = | + | function Machine(x : int) { |
− | + | this.kind = ["bulldozer", "lathe", "car"][x]; | |
− | + | } | |
+ | function announce() { | ||
+ | print("I am a "+this.kind+"."); | ||
+ | } | ||
+ | } | ||
− | + | print(typeof Machine.prototype); // causes a compile-time error | |
− | + | ||
− | == Privacy == | + | var c = new Machine(2); |
+ | |||
+ | c.announce(); // prints "I am a car."</syntaxhighlight><!--</unityscript>--> | ||
+ | |||
+ | === File name matters === | ||
+ | |||
+ | UnityScript tries to save you from typing. Most files represent single classes, so automatically, the name of a UnityScript file is used to define a class which the file's contents are assumed to implement. | ||
+ | |||
+ | For instance, the following file Dog.js: | ||
+ | |||
+ | <syntaxhighlight lang="javascript"> | ||
+ | function Bark() { | ||
+ | Debug.Log("Woof!"); | ||
+ | } | ||
+ | |||
+ | function Wait() { | ||
+ | while () { | ||
+ | } | ||
+ | } | ||
+ | |||
+ | function PlayDead() { | ||
+ | Application.Quit(); | ||
+ | } | ||
+ | </syntaxhighlight> | ||
+ | |||
+ | Is essentially interpreted as the following equivalent C# code: | ||
+ | |||
+ | <syntaxhighlight lang="javascript"> | ||
+ | using UnityEngine; | ||
+ | |||
+ | class Dog : MonoBehaviour { // this means Dog derives from MonoBehaviour | ||
+ | |||
+ | public void Bark() { // These are methods of Dog. Note that they are automatically public. | ||
+ | Debug.Log("Woof!"); | ||
+ | } | ||
+ | |||
+ | public void Wait() { | ||
+ | while () { | ||
+ | } | ||
+ | } | ||
+ | |||
+ | public void PlayDead() { | ||
+ | Application.Quit(); | ||
+ | } | ||
+ | |||
+ | } | ||
+ | </syntaxhighlight> | ||
+ | |||
+ | JavaScript just executes code, with no regard to the file the code is stored in. | ||
+ | |||
+ | == Syntax == | ||
+ | |||
+ | === Semicolons are "more required" === | ||
+ | |||
+ | While JavaScript tries to make semicolons unnecessary, the approach it takes, often dubbed "semicolon insertion," is not always perfect. This often leaves JavaScript developers with buggy code and confused minds. So, UnityScript avoids this trouble by simply requiring semicolons and not trying to insert them by itself. | ||
+ | |||
+ | Semicolons are required in several places (pretty much after everything): | ||
+ | * After <code>return</code>, <code>continue</code>, or <code>break</code> statements. | ||
+ | * After expression statements. | ||
+ | ::<syntaxhighlight lang="javascript">transform.Translate(0, 0, 5);</syntaxhighlight> | ||
+ | * After variable declarations. | ||
+ | * After variable assignment. | ||
+ | * After a bodiless method declaration (such as in an interface). | ||
+ | * Between the parameters in a <code>for</code> loop. | ||
+ | |||
+ | === One variable declaration at a time === | ||
+ | |||
+ | JavaScript supports multiple variable declarations in one <code>var</code> statement. | ||
+ | <syntaxhighlight lang="javascript">var x = 3, y = 4;</syntaxhighlight> | ||
+ | UnityScript does not. | ||
+ | |||
+ | === Assignment cannot be an expression === | ||
+ | |||
+ | In JavaScript, assignment is treated as an expression. | ||
+ | |||
+ | <syntaxhighlight lang="javascript">var x = 3; // x is 3 | ||
+ | var y = (x=x+2); // x is 5, y is 5</syntaxhighlight> | ||
+ | |||
+ | In Unity, assignment is always a statement, so this must be broken up into steps. | ||
+ | <syntaxhighlight lang="javascript">var x = 3; // x is 3 | ||
+ | // var y = (x=x+2); // Error! | ||
+ | x = x + 2; // x is 5 | ||
+ | var y = x; // y is 5</syntaxhighlight> | ||
+ | |||
+ | The exceptions are the [pre/post]-[in/de]crement operations: | ||
+ | <syntaxhighlight lang="javascript">var x = 3; | ||
+ | var y = x++; // x is 4, y is 3 | ||
+ | |||
+ | x = 3; | ||
+ | var z = ++x; // x is 4, z is 4</syntaxhighlight> | ||
+ | |||
+ | === No Global Variables === | ||
+ | |||
+ | Every top-level variable in JavaScript is global. Additionally, any variable declaration not preceded by the <code>var</code> statement is automatically scoped to be global. This is not the case in UnityScript; there are not really any global variables in UnityScript per sé. | ||
+ | |||
+ | === Dynamic typing can be inefficient === | ||
+ | |||
+ | Both UnityScript and Javascript support dynamic typing. | ||
+ | |||
+ | <syntaxhighlight lang="javascript"> | ||
+ | var x; | ||
+ | x = 3; | ||
+ | x = new Array(); // works in both UnityScript and JavaScript | ||
+ | </syntaxhighlight> | ||
+ | |||
+ | However, in UnityScript, when one uses this feature, it can become inefficient to access x many times. This is because the compiler recognizes that the type of the object may change over time. Therefore, the compiler basically produces what would be produced by the following C# code: | ||
+ | |||
+ | <syntaxhighlight lang="csharp"> | ||
+ | Object x; | ||
+ | x = 3; | ||
+ | x = new Array(); | ||
+ | </syntaxhighlight> | ||
+ | |||
+ | This works just fine. Anything can be cast to an object. But when you want to call a method on x, such as Push: | ||
+ | |||
+ | <syntaxhighlight lang="csharp"> | ||
+ | var x; | ||
+ | x = 3; | ||
+ | x = new Array(); | ||
+ | x.Push(2); // Error! BCE0019: 'Push' is not a member of 'Object'. | ||
+ | </syntaxhighlight> | ||
+ | |||
+ | Basically the compiler doesn't know what type to cast x to. So we have to do it ourselves by replacing the last line with something like <code>(x cast Array).Push(2);</code>, and a lot of casting can make things inefficient. | ||
+ | |||
+ | If we never change the type of x, however, the compiler will recognize this and not use the Object datatype for our variable. | ||
+ | |||
+ | <syntaxhighlight lang="javascript"> | ||
+ | var x; | ||
+ | x = 3; | ||
+ | x += 1; | ||
+ | WriteToFile(x); | ||
+ | // x is typed as an integer because we only use one type throughout our program | ||
+ | </syntaxhighlight> | ||
+ | |||
+ | By contrast to all of this, in JavaScript, everything is dynamically typed, so instead of having an inefficient dynamic typing system, everything in JavaScript is inefficient. | ||
+ | |||
+ | === Privacy === | ||
In JavaScript, privacy is rather unconventional. | In JavaScript, privacy is rather unconventional. | ||
− | <javascript>function Person() { // (this is the *JavaScript* way of doing privacy) | + | <syntaxhighlight lang="javascript">function Person() { // (this is the *JavaScript* way of doing privacy) |
var secret = "I am a mass murderer."; // private | var secret = "I am a mass murderer."; // private | ||
this.speak = function() { print("Don't make me tell you my secret! "+secret); }; // prints secret | this.speak = function() { print("Don't make me tell you my secret! "+secret); }; // prints secret | ||
Line 41: | Line 190: | ||
var bob = new Person(); | var bob = new Person(); | ||
print(bob.secret); // undefined | print(bob.secret); // undefined | ||
− | bob.speak(); // prints "Don't make me tell you my secret! I am a mass murderer."</ | + | bob.speak(); // prints "Don't make me tell you my secret! I am a mass murderer."</syntaxhighlight> |
In UnityScript, it can be more intuitive. | In UnityScript, it can be more intuitive. | ||
− | <!--<unityscript>--><javascript>class Person { // UnityScript only; impossible in JavaScript | + | <!--<unityscript>--><syntaxhighlight lang="javascript">class Person { // UnityScript only; impossible in JavaScript |
private var secret : String; | private var secret : String; | ||
function Person() { | function Person() { | ||
Line 57: | Line 206: | ||
var bob = new Person(); | var bob = new Person(); | ||
print(bob.secret); // undefined | print(bob.secret); // undefined | ||
− | bob.speak(); // prints "Don't make me tell you my secret! I am a mass murderer."</ | + | bob.speak(); // prints "Don't make me tell you my secret! I am a mass murderer."</syntaxhighlight><!--</unityscript>--> |
+ | |||
+ | === No Bling === | ||
+ | |||
+ | Dollar signs ($) are not allowed in UnityScript identifiers as they are in JS identifiers. (In JS, the symbol is often used for c-style namespacing or as the name of a do-everything function.) | ||
+ | |||
+ | <syntaxhighlight lang="javascript">var lib$cosine = 3; // ERROR! in UnityScript</syntaxhighlight> | ||
+ | |||
+ | === No <code>with</code> statement === | ||
+ | |||
+ | There is no <code>with</code> statement in UnityScript. This is probably for the best, as JavaScript's <code>with</code> statement causes the whole language to be slower, regardless of whether the statement is used or not. It is also considered harmful. | ||
+ | |||
+ | === UnityScript has .NET's OOP features === | ||
+ | |||
+ | UnityScript supports classes, as well as "protection levels" (public, private, protected) and "static" keyword options. Since it also supports explicit typing, it also has support for "generics" (runtime type enforcement), which JavaScript has no notion of. | ||
+ | |||
+ | === No <code>delete</code> in UnityScript === | ||
+ | |||
+ | JavaScript allows a way for you to remove declared variables from the namespace. UnityScript doesn't. | ||
+ | |||
+ | === No Regular Expression Literals (RegExp or regex) === | ||
+ | |||
+ | In JavaScript (and even JScript.NET, the language on which UnityScript is based), one can directly define a regular expression using a syntax like the following: | ||
+ | |||
+ | <syntaxhighlight lang="javascript">var sentence = /[A-Z].*[\.\?!]/; // JavaScript/JScript.NET only</syntaxhighlight> | ||
+ | |||
+ | UnityScript does not support this, understandably, as regular expressions are pretty uncommon in game code, and the syntax is hard to tokenize/lex. | ||
+ | |||
+ | === The <code>this</code> keyword === | ||
+ | |||
+ | In JavaScript, <code>this</code> refers to something called the "context". It's basically a variable that's set in a different way than other variables are set, and can have practically any value except for <code>null</code> or <code>undefined</code>. | ||
+ | |||
+ | In UnityScript, <code>this</code> only ever means one thing: basically, the object on which a method is being called. | ||
+ | |||
+ | <syntaxhighlight lang="javascript">class Person { | ||
+ | var species : String; | ||
+ | var eyeColor : String; | ||
+ | var hairColor : String; | ||
+ | function Person(eyeColor : String) { | ||
+ | species = "homo sapiens"; // we could also say this.species and it would be the same. | ||
+ | this.eyeColor = eyeColor; // set the current object's eyeColor field to hold the value of the argument eyeColor. | ||
+ | hairColor = "brown"; | ||
+ | } | ||
+ | }</syntaxhighlight> | ||
+ | |||
+ | Note that without the <code>this.</code> qualifier, by default, an identifier (e.g. <code>hairColor</code>) will refer to a class field (<code>this.hairColor</code>) UNLESS a variable of the same name has already been defined (e.g. the argument eyeColor). In such a case, <code>this.</code> must be explicitly included to disambiguate between the variable name and the field (property) name, as seen on line 7 of the code snippet. When a variable or argument hides the visibility of a field, it is called "shadowing". | ||
− | == | + | == See Also == |
− | + | * [[Bugs in the Unity programming environment]] | |
+ | * [[Head First into Unity with UnityScript]] | ||
− | + | [[Category:JavaScript]] | |
+ | [[Category:Legacy]] |
Latest revision as of 20:49, 21 November 2018
End of support for UnityScript Starting with Unity 2018.2, support for UnityScript (Unity's version of JavaScript) has ended. C# is now the only supported language going forward. You can learn more about the reasons for this change here. There is an official UnityScript-to-C# Automatic Conversion tool to help those wanting to transition their UnityScript projects over to C#. |
Note: This page attempts to explain the differences between JavaScript (ECMAScript) and UnityScript as succinctly and clearly as possible. If you have any suggestions, feel free to add them to the author's talk page.
[edit] Overview
[edit] Terminology
It is not uncommon for Unity developers and even members of Unity Technologies to refer to Unity's JavaScript like language as simply "JavaScript", as if it was equivalent or interchangeable with what most people know of as JavaScript on the web. However, the two are actually very different languages. Although they do resemble each other syntactically they have very different semantics. While "JavaScript" is merely a generic name and could refer to any one of many implementations of the ECMAScript specification, Unity's "JavaScript" language doesn't even come close to conforming to that specification — nor does it try to. It's a proprietary language and it doesn't actually follow any concrete specification of standard JavaScript and is modified at will by the engine developers.
Because of this, the vast majority of JavaScript libraries you find will not work by default in Unity. Unity's "JavaScript" is most similar to Microsoft's JScript.NET, although it is not quite identical. Thus many developers prefer to call the language Unity uses "UnityScript" instead, to help differentiate it. Some people consider this to be "just semantics", but when people call both "JavaScript" it becomes a lot harder to search the nternet for solutions and help related to Unity. It's also quite a lot of trouble to continuously specify whether one is referring to "real" JavaScript or Unity's version. So it's best to just stick with "JavaScript" for real JavaScript and "UnityScript" for Unity's language.
[edit] JavaScript is class-free
JavaScript (i.e. the language that's not UnityScript) has no classes. This is because it's a prototypal language, and not a classical one. Inheritance happens with [more dynamic] objects, rather than [unchanging] classes, in JavaScript.
function Machine(x) { this.kind = ["bulldozer", "lathe", "car"][x]; } var c = new Machine(2); print(typeof c.announce); // "undefined" Machine.prototype.announce = function() { print("I am a "+this.kind+"."); }; print(typeof c.announce); // "function" c.announce(); // prints "I am a car."
As shown above, in JavaScript, a function can create an object, when called with the new
keyword. After that happens, the prototype (template) object Machine can be extended to provide additional functionality, and all class instances, past and future, are affected by this extension.
UnityScript has classes, unlike JavaScript. Also, in UnityScript, once you've defined a class, that class is more or less fixed for the duration of the runtime of your program. (N.B. There may be some exceptions to this rule, such as Reflection, but you probably do not need this and should not be using it because it's not very efficient.) However, the class system has the added benefit of being an easier-to-read, more familiar (to most) language.
class Machine { var kind : String; // fields are public by default function Machine(x : int) { this.kind = ["bulldozer", "lathe", "car"][x]; } function announce() { print("I am a "+this.kind+"."); } } print(typeof Machine.prototype); // causes a compile-time error var c = new Machine(2); c.announce(); // prints "I am a car."
[edit] File name matters
UnityScript tries to save you from typing. Most files represent single classes, so automatically, the name of a UnityScript file is used to define a class which the file's contents are assumed to implement.
For instance, the following file Dog.js:
function Bark() { Debug.Log("Woof!"); } function Wait() { while () { } } function PlayDead() { Application.Quit(); }
Is essentially interpreted as the following equivalent C# code:
using UnityEngine; class Dog : MonoBehaviour { // this means Dog derives from MonoBehaviour public void Bark() { // These are methods of Dog. Note that they are automatically public. Debug.Log("Woof!"); } public void Wait() { while () { } } public void PlayDead() { Application.Quit(); } }
JavaScript just executes code, with no regard to the file the code is stored in.
[edit] Syntax
[edit] Semicolons are "more required"
While JavaScript tries to make semicolons unnecessary, the approach it takes, often dubbed "semicolon insertion," is not always perfect. This often leaves JavaScript developers with buggy code and confused minds. So, UnityScript avoids this trouble by simply requiring semicolons and not trying to insert them by itself.
Semicolons are required in several places (pretty much after everything):
- After
return
,continue
, orbreak
statements. - After expression statements.
transform.Translate(0, 0, 5);
- After variable declarations.
- After variable assignment.
- After a bodiless method declaration (such as in an interface).
- Between the parameters in a
for
loop.
[edit] One variable declaration at a time
JavaScript supports multiple variable declarations in one var
statement.
var x = 3, y = 4;
UnityScript does not.
[edit] Assignment cannot be an expression
In JavaScript, assignment is treated as an expression.
var x = 3; // x is 3 var y = (x=x+2); // x is 5, y is 5
In Unity, assignment is always a statement, so this must be broken up into steps.
var x = 3; // x is 3 // var y = (x=x+2); // Error! x = x + 2; // x is 5 var y = x; // y is 5
The exceptions are the [pre/post]-[in/de]crement operations:
var x = 3; var y = x++; // x is 4, y is 3 x = 3; var z = ++x; // x is 4, z is 4
[edit] No Global Variables
Every top-level variable in JavaScript is global. Additionally, any variable declaration not preceded by the var
statement is automatically scoped to be global. This is not the case in UnityScript; there are not really any global variables in UnityScript per sé.
[edit] Dynamic typing can be inefficient
Both UnityScript and Javascript support dynamic typing.
var x; x = 3; x = new Array(); // works in both UnityScript and JavaScript
However, in UnityScript, when one uses this feature, it can become inefficient to access x many times. This is because the compiler recognizes that the type of the object may change over time. Therefore, the compiler basically produces what would be produced by the following C# code:
Object x; x = 3; x = new Array();
This works just fine. Anything can be cast to an object. But when you want to call a method on x, such as Push:
var x; x = 3; x = new Array(); x.Push(2); // Error! BCE0019: 'Push' is not a member of 'Object'.
Basically the compiler doesn't know what type to cast x to. So we have to do it ourselves by replacing the last line with something like (x cast Array).Push(2);
, and a lot of casting can make things inefficient.
If we never change the type of x, however, the compiler will recognize this and not use the Object datatype for our variable.
var x; x = 3; x += 1; WriteToFile(x); // x is typed as an integer because we only use one type throughout our program
By contrast to all of this, in JavaScript, everything is dynamically typed, so instead of having an inefficient dynamic typing system, everything in JavaScript is inefficient.
[edit] Privacy
In JavaScript, privacy is rather unconventional.
function Person() { // (this is the *JavaScript* way of doing privacy) var secret = "I am a mass murderer."; // private this.speak = function() { print("Don't make me tell you my secret! "+secret); }; // prints secret } var bob = new Person(); print(bob.secret); // undefined bob.speak(); // prints "Don't make me tell you my secret! I am a mass murderer."
In UnityScript, it can be more intuitive.
class Person { // UnityScript only; impossible in JavaScript private var secret : String; function Person() { secret = "I am a mass murderer."; } function speak() { print("Don't make me tell you my secret! "+secret); } } var bob = new Person(); print(bob.secret); // undefined bob.speak(); // prints "Don't make me tell you my secret! I am a mass murderer."
[edit] No Bling
Dollar signs ($) are not allowed in UnityScript identifiers as they are in JS identifiers. (In JS, the symbol is often used for c-style namespacing or as the name of a do-everything function.)
var lib$cosine = 3; // ERROR! in UnityScript
[edit] No with
statement
There is no with
statement in UnityScript. This is probably for the best, as JavaScript's with
statement causes the whole language to be slower, regardless of whether the statement is used or not. It is also considered harmful.
[edit] UnityScript has .NET's OOP features
UnityScript supports classes, as well as "protection levels" (public, private, protected) and "static" keyword options. Since it also supports explicit typing, it also has support for "generics" (runtime type enforcement), which JavaScript has no notion of.
[edit] No delete
in UnityScript
JavaScript allows a way for you to remove declared variables from the namespace. UnityScript doesn't.
[edit] No Regular Expression Literals (RegExp or regex)
In JavaScript (and even JScript.NET, the language on which UnityScript is based), one can directly define a regular expression using a syntax like the following:
var sentence = /[A-Z].*[\.\?!]/; // JavaScript/JScript.NET only
UnityScript does not support this, understandably, as regular expressions are pretty uncommon in game code, and the syntax is hard to tokenize/lex.
[edit] The this
keyword
In JavaScript, this
refers to something called the "context". It's basically a variable that's set in a different way than other variables are set, and can have practically any value except for null
or undefined
.
In UnityScript, this
only ever means one thing: basically, the object on which a method is being called.
class Person { var species : String; var eyeColor : String; var hairColor : String; function Person(eyeColor : String) { species = "homo sapiens"; // we could also say this.species and it would be the same. this.eyeColor = eyeColor; // set the current object's eyeColor field to hold the value of the argument eyeColor. hairColor = "brown"; } }
Note that without the this.
qualifier, by default, an identifier (e.g. hairColor
) will refer to a class field (this.hairColor
) UNLESS a variable of the same name has already been defined (e.g. the argument eyeColor). In such a case, this.
must be explicitly included to disambiguate between the variable name and the field (property) name, as seen on line 7 of the code snippet. When a variable or argument hides the visibility of a field, it is called "shadowing".