Chapter 11
Use the
Number
âÂÂsprototype
property:Number.prototype.triple = function (âÂÂâÂÂ) { var nm = this.valueOf(âÂÂâÂÂ) * 3; return nm; } var num = new Number(3.0); alert(num.triple(âÂÂâÂÂ));
Declare the data member with
var
instead ofthis
. The purpose behind data hiding is to control how the data is accessed or updated.Use the
throw
statement to trigger an error. Then implementtry...catch
in the calling application:if (typeof value != "number") { throw "NotANumber"; }
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.
HereâÂÂs one approach to creating the objects:
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.