The file 1-list.js below shows how to declare a OO-style class in JavaScript.
Note that the only things assigned to properties of this
are anonymous functions. These are the "methods" of the class that access "private" properties. JavaScript doesn't have the keyword
private like some other languages. Instead, the "private data members" of a class are the local variables and parameters of the
class constructor. Most JavaScript code in the wild doesn't attempt to make anything "private" which is just bad OO design. Here, the
"methods" are functions nested inside the constructor to give them access to the constructors local variables.
Typical JavaScript code you
see in the wild would have placed the methods as properties of List.prototype which allows for
OO-like method invocation syntax using the
instance as an implicit first argument named this
, but is
really semantically equivalent to using a Java static method that takes the instance as an explicit first argument like
List.pop(List list)
. A static method in Java doesn't have access to private data members of the instance, which isn't a
problem if you have
made all the data members public. Instead of nesting the code for front
in the constructor, we could have gotten
the same functionality by
(with less efficiency) by inserting code between the }
at the end of the constructor and the }
at the end of the class
something like
front() {
var top=this.pop();
this.push(top);
return top;
}
In ES5, this would have been code like
List.prototype.front = function() {...};
Both of these constructs are essentially like Java code
static <T> T front(List<T> list) {
T top=list.pop();
list.push(top);
return top;
}
However, in JavaScript we can say var s = list.front()
whereas the equivalent in Java would be String s = List<String>.front(list)
The capitalization convention in JavaScript, as in Java, is to give classes capitalized names, but to give functions, methods, variables, and such camelCase names.
In ES6, the syntax is more "Java-like" than in ES5 where the class constructor is a function with a capitalized name so rather than
being class List { constructor() { ... } }
ES5 would have function List() { ... }
Note that there is no need for a class Node
and we simply use object literals to construct the "Node" objects. In fact, the only real
need for using the a class is if we want to subclass it or use its prototype
property. We could have defined something essentially
equivalent like
function newList() {
var head = null;
var tail = null;
var _length = 0;
return {
push: function(item) {
...
},
front: function() {...},
back: funcition() {...}
...
};
}