Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Let me try to explain using the following:</p> <pre><code>// Scope 1 var Person = function (_id,_nm) { // Scope 2 var id, name; this.id = _id; this.name = _nm; return { // Scope 3 setName: function (nm) { name = nm; }, getName: function () { return name; }, getId: function () { return id; }, print: function () { $("#output").append("&lt;p&gt;Id: "+id+"; Name: "+name + "&lt;p/&gt;"); } } } </code></pre> <p>The <code>print</code> method will return <code>undefined</code> because you are referring to the <code>var id, name;</code> that is never set in your code. You set the <code>_id</code> and <code>_name</code> to the property <code>id</code> and <code>name</code> but you fail to return the object that you just created. Instead, you return a dictionary, that references the <code>name</code> and <code>id</code> variable you created in <code>Scope 2</code> that you never set, hence the undefined output in the <code>print()</code> call.</p> <p>Here is what you should have done:</p> <pre><code>var NewPerson = function (_id,_nm) { var self = this; this.id = _id; this.name = _nm; this.print = function () { $("#output").append("&lt;p&gt;New Person Id: "+this.id+"; Name: "+ this.name + "&lt;p/&gt;"); }; return this; }; var nperson = new NewPerson(456, "Marcos"); nperson.print(); </code></pre> <p>This will output:</p> <pre><code>New Person Id: 456; Name: Marcos </code></pre> <p>In essence, <code>new</code> is creating a new object represented by <code>this</code>, and you must return <code>this</code> to have a reference to the object created. In fact, if you do not use the <code>new</code> before creating an object, you end up referencing a global instance of <code>this</code>. Try the following:</p> <pre><code>var nperson = new NewPerson(456, "Marcos"); this.name = "Hello"; nperson.print(); var nperson1 = NewPerson(456, "Marcos"); this.name = "Hello"; nperson1.print(); </code></pre> <p>You will see that the first output will be as expected:</p> <pre><code>New Person Id: 456; Name: Marcos </code></pre> <p>But the second will pick up the change made to <code>this.name</code>:</p> <pre><code>New Person Id: 456; Name: Hello </code></pre> <p><a href="http://jsfiddle.net/marcoslin/5vp2R/2/" rel="nofollow">Here is the JSFiddle</a>.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

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