UnityScript versus JavaScript

From Unify Community Wiki
Revision as of 17:54, 10 April 2011 by Ppeterson (Talk | contribs)

Jump to: navigation, search

Contents

JavaScript is class-free

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. <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();</javascript>

UnityScript has classes, and functions cannot create objects as in JavaScript. <javascript> class

Dynamic typing is inefficient

This code is valid in both UnityScript and JavaScript: <javascript>var x; x = 3;</javascript> However, it is inefficient in UnityScript because it causes x to be dynamically typed. For faster runtime execution, use one of the two static typing syntaxes. <javascript>var x = 3; // type `int` is inferred, typed statically</javascript>

<javascript>var x : int; // typed statically x = 3;</javascript>

Privacy

In JavaScript, privacy is rather unconventional.

<javascript>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."</javascript>

In UnityScript, it can be more intuitive.

<javascript>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."</javascript>

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.)

<javascript>var lib$cosine = 3; // ERROR! in UnityScript</javascript>

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.

Personal tools
Namespaces

Variants
Actions
Navigation
Extras
Toolbox