Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p><strong><a href="http://jsfiddle.net/alexflav23/y7Xbb/2/" rel="nofollow">Working fiddle</a></strong></p> <p>The reason is because you are using <code>public</code> members for the <code>Person.prototype</code>. You don't need to add <code>this</code> references to these two. So delete:</p> <pre><code>this.id = _id; this.name = _nm; </code></pre> <p>and simply use:</p> <pre><code> var id = _id, name = _nm; </code></pre> <p>Now everything will work fine. The whole idea is to use <code>var</code>, and not <code>this</code>, otherwise a closure will not be created. Now you will not be able to access <code>name</code> and <code>id</code> directly, instead you will have to use <code>setName(), getName(), setId(), getId()</code> etc.</p> <p>The two members, <code>id</code> and <code>name</code>, will now become closures as you want them to be.</p> <p><strong>Update</strong></p> <p>If you used <code>this.id</code>, then it wouldn't have been <code>private</code> and you could just do <code>var p = new Person(1, "Mahesha");</code> and access <code>p.name</code> or <code>p.id</code> directly. They are supposed to be <code>private</code> so this is not what you want.</p> <p>With the closure pattern, p.name and p.id are undefined and can only be accessed through <code>p.getName();</code> and <code>p.getId();</code>. Read on how closures work. The idea is that because you are using that <code>var name</code>, a closure will be created to remember it's value.</p> <p>Your <code>getName</code> and <code>setName</code> are using that closure to access the <code>name</code> property. There is no <code>this.name</code>, there is a value remembered through a higher - order closure.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload