Chapter 11

  1. Use the Number’s prototype property:

  2. Number.prototype.triple = function (  ) {
       var nm = this.valueOf(  ) * 3;
       return nm;
    }
    var num = new Number(3.0);
    alert(num.triple(  ));
  3. Declare the data member with var instead of this. The purpose behind data hiding is to control how the data is accessed or updated.

  4. Use the throw statement to trigger an error. Then implement try...catch in the calling application:

  5. if (typeof value != "number") {
      throw "NotANumber";
    }
  6. Unlike the event object, there are more than just model differences involved. Not only is the property different, but so is the value that’s assigned to the property.

  7. Here’s one approach to creating the objects:

  8. function Control(  ) {
      var state = 'on';
      var background = '#fff';
    
      this.changeState = function(  ) {
          if (state == 'on') {
              state = 'off';
              background = '#000';
          } else
              state = 'on';
              background = '#fff';
         };
    
      this.getState = function(  ) {
         return state;
      };
    
      this.getColor = function(  ) {
         return background;
      };
    }

Get Learning JavaScript now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.