Objects and Prototypes

R. Alexander Miłowski

milowski@ischool.berkeley.edu

School of Information, UC Berkeley

Constructing Objects

Every function can be used to construct an object.

function X() {
   this.value = 12;
}
var y = X()
var z = new X();
         
  1. What is the value of y and z?
  2. What does the assignment of this.value do?
  3. What is this for both function executions?
  4. What is z.__proto__?

Objects

Objects all have a prototype that:

Prototypes in inherit by a chaining prototypes.

(complicated and questionable in use)

Using Prototypes

Methods and properties are defined using the prototype property of a function.

Weird, huh?

function Dozen() { 
   this.value = 12; 
}
Dozen.prototype.numberOfItems = function(x) {
   return x*this.value;
}
Dozen.prototype.numberOfUnits = function(x) {
   return x/this.value;
}
         

Getters and Setters

A object property can be controlled by functions:

var Audio = {
   _volume: 7,
   get volume() {
      return this._volume;
   },
   set volume(level) {
      if (level<0 || level >10) {
         throw "Invalid value";
      }
      this._volume = level;
   }
}      
         

Now, Audio.volume = 11 throws an error.

What about Audio._volume ?

Defining Properties

The value is hidden with a closure:

function Audio() {
   var audioLevel = 7;
   Object.defineProperty(
      this,"volume", {
         get: function() {
            return audioLevel;
         },
         set: function(level) {
            if (level<0 || level >10) {
               throw "Invalid value";
            }
            audioLevel = level;
         }
      }
   );
}
There are too many tricks in JavaScript to name to make up for the fact it isn't designed all that well.

Inheritance

Here be dragons

function Dragon() {
   this.__proto__.__proto__.constructor();
   // Yes, inherited constructors do not execute by default
}
Dragon.prototype.breathFire = function() {
   console.log("Hot, hot, hot!");
}
Dragon.prototype.__proto__ = WingedCreature.prototype;
function WingedCreature() {
   this.numberOfWings = 2;
}
WingedCreature.prototype.fly = function() {
   console.log("I can fly.  Whoohoo!");
}