Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>I think this is the structure you are looking for:</p> <pre><code>function PrivateFunc(private, public){ this.privateVar = private; this.publicVar = public; } function PublicFun(public){ this.publicVar = public; if(this.publicVar == null)this.publicVar = 'This is a public variable.'; this.PrivateFun = function(private){ return new PrivateFunc(private, this.publicVar); } } var pf = new PublicFun('public variable'); var pv = pf.PrivateFun('private variable'); console.log('pf.publicVar = '+pf.publicVar); console.log('pf.privateVar = '+pf.privateVar); console.log('pv.publicVar = '+pv.publicVar); console.log('pv.privateVar = '+pv.privateVar); </code></pre> <p>Notice that <code>PrivateFunc</code> is not <code>PrivateFun</code>. The real factor comes down to the key word <code>this</code>. <code>this</code> refers to the current Object as when you type <code>this</code>. <code>var</code> is only accessible inside your method. You should think of a <b>JavaScript</b> Object as an Associative Array. If that doesn't suit your needs try:</p> <pre><code>var jsObject = { publicVar: null, PrivateFun: function(private){ var privateVar = private; //cannot access with dot return this; }, PublicFun: function(public){ this.publicVar = public; if(this.publicVar == null)this.publicVar = 'This is a public variable'; return this; } } var pf = jsObject.PublicFun(); var pv = jsObject.PrivateFun('private variable'); console.log('pf.publicVar = '+pf.publicVar); console.log('pf.privateVar = '+pf.privateVar); console.log('pv.publicVar = '+pv.publicVar); console.log('pv.privateVar = '+pv.privateVar+' //cannot access with dot'); </code></pre> <p>Note that Object Literals are not Constructors, so you cannot make <code>new</code> instances. Also, in the Object Literal case, <code>var privateVar</code> is virtually useless, unless you don't want the <code>privateVar</code> returned. <code>this</code> must be returned in order to access jsObject, which holds the reference to <code>publicVar</code>.</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