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:

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

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 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 and name. Notice how the parameter of the marry() method shadows the private variable name, while 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.