You can achieve the same privacy level by using an anonymous immediate function. An immediate function is wrapped in brackets and executes immediately.
The example below demonstrates enclosure with an immediate function. The function's closure maintains the value of author. Furthermore, notice that the book object is created with object literal notation.
Run
- var book; // public object declaration
- (function () { // anonymous immediate function
- var author = "James Joyce"; // private member
- book = {
- getAuthor: function () { // privileged method
- return author;
- }
- };
- }());
- alert(book.author); // => undefined (author is private)
- alert(book.getAuthor()); // => James Joyce (privileged method)
Similar to the earlier example, the getAuthor() method is also privileged with privileged access to the local private variable author.
Anonymous immediate functions are frequently used in modern JavaScript applications and are also used extensively in our JavaScript + jQuery Design Pattern Framework. Click here to learn more.
No comments:
Post a Comment