API, and your applications will work on all browsers automatically. At least
the parts that access the serial port—all other parts will still be subject to
browser incompatibilities, of course.
In this section, we’ll create a
SerialDevice
class that we can use in many of our
projects. It’s based on one of the standard Google Chrome app samples,
9
and
you should have a look at the other samples, too. Studying them is a great
way to learn.
Creating classes in JavaScript isn’t difficult, but it’s completely different from
most other object-oriented languages you might know. JavaScript’s object
system is based on prototypes, not classes. Instead of providing a template
(class) for creating new objects, you create new objects immediately. Then
you refine these objects and can use them afterward as a template (or parent)
for other objects.
Despite all differences between class-based and prototype-based languages,
you have to create your objects somehow. In JavaScript, you can use a con-
structor function:
ChromeApps/SerialDevice/js/serial_device.js
var SerialDevice = function(path, baudRate) {
Line 1
this.path = path;
-
this.baudRate = baudRate || 38400;
-
this.connectionId = -1;
-
this.readBuffer = "";
5
this.boundOnReceive = this.onReceive.bind(this);
-
this.boundOnReceiveError = this.onReceiveError.bind(this);
-
this.onConnect = new chrome.Event();
-
this.onReadLine = new chrome.Event();
-
this.onError = new chrome.Event();
10
};
-
Using this function you can create new
SerialDevice
objects like this:
var arduino = new SerialDevice("/dev/tty.usbmodem24321");
Note the frequent use of the
this
keyword. In JavaScript,
this
refers to the cur-
rent function’s execution context. You can use it for various purposes. When
creating objects, you’ll most often use it to create attributes and methods
that are bound to a certain object. In lines 2 to 5, we use it to define a few
instance variables, such as
path
.
In the following two lines, we use it to define two more instance variables.
This time, we use
this
also on the right-hand side of the assignment and pass
9.
https://github.com/GoogleChrome/chrome-app-samples/tree/master/samples/serial/ledtoggle
report erratum • discuss
Writing a SerialDevice Class • 275
www.it-ebooks.info