Wednesday, October 8, 2008

We are all adults here, right?

I've been wondering for a while: why don't I see this style of OOP "private" variables too often in Javascript:

var MyClass = function() {}
MyClass.prototype = {
  __hello : "hello",
  __world : "world",
  sayHelloWorld : function() {
    return this.__hello + " " + this.__world;
  },
  sayWorldHello : function() {
    return this.__world + " " + this.__hello;
  }
}

It strikes me as an easier way to handle inheritance. For example, consider the traditional alternative:

var MyClass = function() {
  var hello = "hello"
  var world = "world"
  this.sayHelloWorld = function() {
    return hello + " " + world;
  }
  this.sayWorldHello = function() {
    return world + " " + hello;
  }
}

How do we extend this so that the private variable world always has a value of "world!!" (with exclamation marks)? How do I label it protected, instead of private?

Rather than engineering mechanisms to prevent people from editing our variables (which anyone with Notepad and your source file could do), wouldn't we benefit from having more value with less (but more "risky") code?

No comments:

Post a Comment