UnityScript versus JavaScript

From Unify Community Wiki
(Difference between revisions)
Jump to: navigation, search
(JavaScript is class-free)
(JavaScript is class-free)
Line 5: Line 5:
 
   this.kind = ["bulldozer", "lathe", "car"][x];
 
   this.kind = ["bulldozer", "lathe", "car"][x];
 
}
 
}
 +
 
var c = new Machine(2);
 
var c = new Machine(2);
 
print(typeof c.announce); // "undefined"
 
print(typeof c.announce); // "undefined"
Line 14: Line 15:
 
print(typeof c.announce); // "function"
 
print(typeof c.announce); // "function"
 
c.announce();</javascript>
 
c.announce();</javascript>
 +
 +
UnityScript has classes, and functions cannot create objects as in JavaScript.
 +
<!--<unityscript--><javascript>
 +
class
  
 
== Dynamic typing is inefficient ==
 
== Dynamic typing is inefficient ==

Revision as of 17:58, 7 April 2011

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() {

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

Personal tools
Namespaces

Variants
Actions
Navigation
Extras
Toolbox