JavaScript: The Definitive Guide, Sixth Editio javaScript权威指南(第6版) pdf 文字版-文字版, javascript电子书, 和javascript 有关的电子书:

9.8.3 Encapsulating Object State

9.8.3 Encapsulating Object State

§9.6.6 and Example 9-10 showed how you can use variables or arguments of a constructor function as private state for the objects created by that constructor. The shortcoming of this technique is that in ECMAScript 3, the accessor methods that provide access to that state can be replaced. ECMAScript 5 allows us to encapsulate our state variables more robustly by defining property getter and setter methods that cannot be deleted. Example 9-21 demonstrates.

Example 9-21. A Range class with strongly encapsulated endpoints

// This version of the Range class is mutable but encapsulates its endpoint // variables to maintain the invariant that from <= to. function Range(from, to) {

// Verify that the invariant holds when we're created

if (from > to) throw new Error("Range: from must be <= to");

// Define the accessor methods that maintain the invariant

function getFrom() { return from; }

function getTo() { return to; }

function setFrom(f) { // Don't allow from to be set > to

if (f <= to) from = f;

else throw new Error("Range: from must be <= to");


function setTo(t) { // Don't allow to to be set < from

if (t >= from) to = t;

else throw new Error("Range: to must be >= from");


// Create enumerable, nonconfigurable properties that use the accessors

Object.defineProperties(this, {

from: {get: getFrom, set: setFrom, enumerable:true, configurable:false},

to: { get: getTo, set: setTo, enumerable:true, configurable:false }

}); }

// The prototype object is unchanged from previous examples. // The instance methods read from and to as if they were ordinary properties. Range.prototype = hideProps({

constructor: Range,

includes: function(x) { return this.from <= x && x <=; },

foreach: function(f) {for(var x=Math.ceil(this.from);x<;x++) f(x);},

toString: function() { return "(" + this.from + "..." + + ")"; } });

友情链接It题库(| 版权归yishouce.com所有| 友链等可联系|粤ICP备16001685号-1