Advertisement
wtmhahagd

Java to JS

Nov 30th, 2013
109
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 6.67 KB | None | 0 0
  1. FROM JAVA TO JS: A GUIDE
  2.  
  3. So you're a seasoned (or not, heh) programmer looking to dip your feet into web programming- and that means JavaScript. Thing is, JS does certain things differently that most common languages- and here's all the changes that you should care about.
  4.  
  5. [In this tutorial, I use Java as the "from" language, but any OO language (C++, perhaps?) should be a sufficient background.]
  6.  
  7. DYNAMIC TYPING
  8.  
  9. JavaScript is dynamically typed. Unlike Java, where the type of a variable is of utmost importance, JS doesn't really care. You can see the effects of this in a lot of syntactic changes:
  10.  
  11. VARIABLE INSTANTIATIONS: instead of declaring by type, you have one, solitary var keyword. And a const keyword, which isn't seen as often, but it's there.
  12.  
  13. var x = 5;
  14. x = "Dynamic typing!"
  15.  
  16. FUNCTION HEADERS: again, instead of declaring by return type, you have a function keyword. Note the lack of types for arguments, too:
  17.  
  18. function addNumbers(x, y) {
  19. return x + y;
  20. }
  21.  
  22. The lack of typing here can obviously be both a blessing and a curse- no more casting between doubles and ints, that's for sure, but you've got to be careful that anything that goes into that function is a number, unless accidental string concatenation is okay with you. JS is a very permissive language. The entire responsibility has been placed on you to write good code. Spooky, no?
  23.  
  24. FUNCTION LITERALS: Function literals look wrong. They just do. Your programmer sense will complain the first time you write one, but that's okay: JS understands. Function literals are primarily used to set methods of objects, like elements on a page:
  25.  
  26. someElement.onclick = function() {
  27. alert("Click get!");
  28. }
  29.  
  30. It's quite a weird syntax, but JS will allow you to start your statement as if you were declaring a property, then actually declare a method with a function literal. Doesn't that look strange? Don't worry- that's perfectly normal, both the syntax and your initial perception. It will pass. Well, the latter, at least. We'll see more of this in about X paragraphs.
  31.  
  32. By the way, meet alert(). It creates a simple alert box. It's got a cousin, prompt(), which includes a text input and returns it as a String. Think of it like an easier-to-call JOptionPane.
  33.  
  34. OBJECTS: Alright, here's where things start to deviate heavily. Objects in JS don't follow the usual OO pattern. When it comes to declaring objects, first of all, you have something called an object literal:
  35.  
  36. var objectLiteral = {
  37. number: 5;
  38. sayHi: function() {
  39. alert("Hi!");
  40. }
  41. }
  42.  
  43. Some things of note in that example- notice the var keyword to initialize, the lack of var keywords for the properties, the colons instead of equals signs (this is the only time JS uses this, by the way), the function literal to declare the method. Note that we can still call objectLiteral.sayHi(), even though when we initially name the method we don't have parentheses. Confused yet?
  44.  
  45. When it comes to declaring classes, there's no class keyword. Instead, you declare it implicitly via a constructor.
  46.  
  47. function Class(num) {
  48. this.number = num;
  49. this.sayHi = function() {
  50. alert("Hi!");
  51. }
  52. }
  53.  
  54. var instance = new Class(5);
  55. instance.sayHi();
  56.  
  57. Notice how we're still not using a var keyword- if the property being referenced doesn't exist, JS will simply go ahead and create one. You can see this behavior in action with the onClick example above.
  58.  
  59. A unique property of constructors (and all functions, but specifically for constructors) in JS: If you define a constructor with multiple arguments, you can call it later on with fewer arguments, and any not specified will default to null. JS doesn't provide any method of multiple constructors for a single class, seing as the constructor is the class definition; use this property and some clever argument ordering instead.
  60.  
  61. function Constructor(par1, par2, par3) {
  62. if (par1 != null) {
  63. this.prop1 = par1;
  64. } else {
  65. this.prop1 = someDefaultValue;
  66. }
  67. //et cetera...
  68. }
  69.  
  70. var instance1 = Constructor(1, 2, 3); //prop1, prop2, and prop3 given values
  71. var instance2 = Constructor(1, 2); //prop3 is null; given default value manually (hopefully)
  72.  
  73. The property and method we created are instance methods, by the way. This becomes important in 3... 2... 1...
  74.  
  75. CLASS METHODS: Every JavaScript object has a prototype. Prototypes are JS's way of simulating class methods and properties- they're definitely not the same, but you can get pretty darn close to the behavior you expect.
  76.  
  77. There are two ways you can set class properties and methods, with varying levels of scope:
  78.  
  79. Via prototype, you create a class property or method that both gives and receives access to the instance properties, i.e., the ones created with this. Again, no need for var keywords, and you'll use function literals here. You set class methods outside of the constructor, since they're not part of the instance:
  80.  
  81. Class.prototype.
  82. Class.prototype.classMethod = function() {
  83. alert("Wow! A class method");
  84. }
  85.  
  86. Or, you can set class properties that do not have access to the instance properties; these are set without prototype:
  87.  
  88. Class.secretNumber = 404;
  89. Class.getSecretNumber = function() {
  90. return secretNumber;
  91. }
  92. Class.secretFormula = function() {
  93. return secretNumber + this.number;
  94. }
  95.  
  96. All the instance properties and methods will know the secretNumber. The class methods getSecretNumber() and secretFormula() have access to the secretNumber as well, but secretFormula, try as it might, cannot access the instance property number, so it will fail.
  97.  
  98. There you have it: two ways of making class methods, with differing scopes; restrict accordingly.
  99.  
  100. INHERITANCE: One of the greatest downfalls, in my opinion, of prototype OO, is the hackiness of inheriting. Sure, it's entirely possible, but it's messy and usually nobody will bother to do it. Instead, I recommend you just maintain any would-be subclasses seperately, and sort of manually inherit- just copy-and-paste whatever methods you need. Is it more of a hassle? Yes. But keep this in mind:
  101.  
  102. One of the ideas behind inheritance is that the subclasses are of type superclass, and so all the subclasses are guaranteed to have all the superclass methods and properties. That makes code like this possible:
  103.  
  104. class Superclass {
  105. public int number() {
  106. return 5;
  107. }
  108. }
  109.  
  110. class Subclass extends Superclass { }
  111.  
  112. public static void main(String[] args) {
  113. Superclass instanceOfSub = new Subclass();
  114. int x = instanceOfSub.number(); // x = 5
  115. }
  116.  
  117. But here's the thing- in JS, type isn't important! So instead of relying on inheritance and a compiler to guarantee a method's there, how about some self-confidence instead? Like I said- JS is a very permissive language- enjoy the freedom, but don't take it as an excuse to get sloppy.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement