Jun 13, 2015

Notes on object-oriented JavaScript for o-o developers (part 5)

This post continues with more notes on distinctive features of object-oriented JavaScript as described in the book The Principles of Object-Oriented JavaScript.

This is a follow-up to the earlier Part 4 and is my final post related to that book.

**  Private properties can be made by using closures.

In JavaScript, all properties of an object are publicly accessible. Unlike some other languages, there are no keyword access modifiers that correspond to public/protected/private.

However, you can get the same effect as private by defining an object in the context of a function that provides local variables and methods that you don't want to be public. The object is then used as a closure on those items that would otherwise not be accessible at all outside of the function.

So here's an example that I have copied from the above book, which nicely illustrates the idea.

  var person = (function () {

    var age = 25;

    return {
      name: "Nick",
      getAge: function () { return age; },
      growOlder: function () { ++age; }
    }

  })();

The outer, anonymously defined function is immediately invoked and returns an object which is assigned to the variable person.

The key concept here is that the two methods of that object refer to a local variable of the function. Because of those references, the lifetime of the local variable is extended, while at the same time it is not visible in any other code.

This use of closures is an example of the Module pattern in JavaScript.

This provides an individual object with a private property, but a similar technique can be used in a constructor so that every object created via the constructor gets its own private, instance property.

  function Person (initial_age) {

    var age = initial_age;

    this.getAge = function () { return age; };
    this.setAge = function (new_age) { age = new_age; };
    this.growOlder = function () { ++age; };

  }

  nick = new Person(59);
  lena = new Person(37);

  console.log(nick.age);  // undefined


Sources:

Closures
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures

Learning JavaScript Design Patterns
http://www.addyosmani.com/resources/essentialjsdesignpatterns/book/


2 comments:

  1. I've found this to be a great resources to explore "closures" further: http://www.amazon.com/You-Dont-Know-JS-Closures/dp/1449335586

    ReplyDelete
  2. That looks like another great book recommendation from you. I'm looking forward to having it help me expand and clarify my understanding of scope and closures in JavaScript.

    ReplyDelete