JavaScript variables and this

Currently I’m taking a more serious look at JavaScript and its concepts. Initially I often got confused about the visibility of variables in an object and how to use the this keyword. So here is a little example as a reminder for myself and anyone who cares:

<html>
<head>
<title>Test</title>
<script type=&#39;text/javascript&#39;>
window.onload = function () {
  var Woman = function () {
    var name = &#39;Nobody&#39;; // Access via name
    this.name = &#39;Alice&#39;; // Access via this.name
    this.marry = function (name) {
      // Nobody is shadowed by the function parameter Bob
      // this.name does not refer to Nobody, but to Alice
      alert(this.name + &#39; married &#39; + name);
    };
  };
  var w = new Woman();
  w.marry(&#39;Bob&#39;); // Alice married Bob
}();
</script>
</head>
<body>
</body>
</html>

In this example we define a constructor for “Woman” objects. Members or methods of an object, that are defined using this, are all public. Hence this.name and this.merry() are public members. Ordinary vars and methods defined using var foo = function () become private members. Therefore var name is a private member. Usually one uses the prototype technique to define public methods for objects. However, those would not be able to access private members. Therefore we use the concept of a “privileged” method marry(), that is public but still has access to private members. From the output of the example above, we can clearly see that there is a difference between this.name and name. Notice how the parameter of the marry() method shadows the private variable name, while this.name is still visible inside the method. If you want to know more about the visibility of object members, read this great article of JavaScript guru Douglas Crockford. He will show you some good patterns to achieve the different behaviours.