HTML and CSS Reference
In-Depth Information
In the constructor, notice the special object this , which we can add properties to. This is the object that is
returned from the constructor. Any variables declared in the constructor function that are not attached to
the this object cannot be directly accessed from outside the constructor.
Prototypes
Using constructors to create object instances is exactly what we'd do in a more class-based language. In
fact, when you see references to classes in JavaScript documentation, this is typically what it's referring to,
the constructor function. Sometimes this terminology overlooks that JavaScript is, in fact, a prototype-
based language.
When you create a new object instance in JavaScript, you actually create a new object that inherits
properties from its constructor object—this is its prototype. You can directly access this object from the
constructor's prototype property. Any properties you assign to the prototype are shared by all objects
derived from its type. Building off the previous example constructor, here is the code:
MyObject.prototype.hello = function () {
console.log("Hello, " + this.name);
};
objA.hello(); //prints: "Hello, Gentle Reader"
var objB = new MyObject("Inspired Coder");
objB.hello(); //prints: "Hello, Inspired Coder"
Here we've added the hello function to the constructor prototype, and in doing so, we added this method
to both object instances: the one previously declared and a newly created object.
Throughout this topic, we create classes (a constructor function and prototype properties) that are shared
across many examples. Typically, we keep these in a separate file that can be imported into documents.
Functional style
One strength of the JavaScript language is that functions are first-class objects. This means you can
assign functions to variables, pass them around, and use them as arguments to other functions. This is a
powerful concept and a feature that is not available in many programming languages. Although the
implications of this idea can be fairly complex, the concept is simple, and something we take advantage of
throughout the topic. If you can understand it, you're on your way to becoming a successful JavaScript
programmer.
You've already used functional arguments earlier in the chapter when you created an animation loop:
setInterval and requestAnimationFrame each take function callbacks as parameters. But, we
can also use functions to structure code clearly. For example, here is a typical for loop used to iterate
over values in an array. We create a counter variable, i , that increments each loop cycle, using it to
access the array values. We've declared an array of three elements and printed each one in turn to the
console:
 
Search WWH ::




Custom Search