Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>You can't do this using an Object literal. <code>this</code> is referring to <code>person</code> <em>after</em> the literal is evaluated, during evaluation <code>this</code> refers to the parent scope. You could wrap the object construction in a function to be sure <code>this</code> refers to the current scope (i.e. the scope of the function). Something like:</p> <pre><code>var person = function(){ this.name = 'John'; this.__test__ = (function(){alert(this.name);}()); return this; }(); </code></pre> <p>Or using variables within the function scope:</p> <pre><code>var person = function(){ var _name = 'John' ,_test = (function(){alert(_name);}()); return { name: _name, __test__: _test }; }(); </code></pre> <p>Or wrap things in a more generic factory function:</p> <pre><code>function objFactory(obj){ var nwObj = {}; for (var l in obj){ if (obj.hasOwnProperty(l)){ if (obj[l] instanceof Function &amp;&amp; /^auto_/i.test(l)){ nwObj[l.replace(/^auto_/i,'')] = obj[l].call(nwObj); } else { nwObj[l] = obj[l]; } } } return nwObj; } //=&gt; usage var person = objFactory( { name: '', auto_name: function(){ this.name='John'; return this.name; } } ); alert(person.name); //=&gt; John </code></pre> <p>And finally (not everyone will agree to this) you could create a load handler in <code>Object.prototype</code>:</p> <pre><code>Object.prototype.load = function(){ for (var l in this){ if (this.hasOwnProperty(l) &amp;&amp; this[l] instanceof Function &amp;&amp; /^auto_/i.test(l)) { this[l].call(this); delete this[l]; } } return this; } //=&gt; usage var person = { name: '', auto_name: function(){this.name='John';} }.load(); alert(person.name); //=&gt; John </code></pre>
    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. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      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