HTML and CSS Reference
In-Depth Information
> obj1.i = "hello world"
Now the next call will return the following:
> obj1.increment()
NaN
The closure-based implementation solves this problem. There is no way to modify the
value of i , or impact the value returned by the function. If a call to the function returns 5,
the next call to the function is guaranteed to return 6.
Data hiding (or encapsulation) is an enormously important concept when writing large ap-
plications. It allows us to write code modules with well-defined public interfaces (or APIs),
while hiding (or encapsulating) the internal logic and state from the caller. This reduces
bugs, since code cannot accidentally corrupt the state of the module.
The approach used to implement the closure-based incrementer is a representation of a
design pattern. A design pattern is a commonly used, reusable approach to solving a com-
mon problem. This approach is referred to as the module design pattern.
The module design pattern is also commonly implemented by returning an object rather
than a function. This allows the object to use private variables for its private properties and
functions, while still exposing a series of public properties and methods. The functionality
above can be rewritten as follows:
> function createIncrementer() {
var i = 0;
return {
increment: function() {
return ++i;
}
};
}
We can now create an incremeter object:
> obj2 = createIncrementer();
Once created, we now call the increment method, and consistently receive a value incre-
mented by 1:
> obj2.increment()
Search WWH ::




Custom Search