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
projects. It s based on one of the standard Google Chrome app samples,
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 =
-
this.onReadLine =
-
this.onError =
10
};
-
Using this function you can create new
var
arduino =
new
Note the frequent use of the
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
In the following two lines, we use it to define two more instance variables.
This time, we use
9.
https://github.com/GoogleChrome/chrome-app-samples/tree/master/samples/serial/ledtoggle
SerialDevice
new
chrome.Event();
new
chrome.Event();
new
chrome.Event();
SerialDevice("/dev/tty.usbmodem24321");
this
keyword. In JavaScript,
path
.
this
also on the right-hand side of the assignment and pass
www.it-ebooks.info
Writing a SerialDevice Class
class that we can use in many of our
SerialDevice
objects like this:
this
refers to the cur-
275
9
and
report erratum
discuss
Need help?
Do you have a question about the Arduino Uno and is the answer not in the manual?