Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Just to mess with Raynos (I wrote this years ago):</p> <p>Private, Public and Static variables</p> <p>The way that we define variables in our Objects determines what methods our Objects have available to access those variables. In JavaScript, there are five levels of methods and properties when working with OO code.</p> <ul> <li><p>Private Declared with 'var variableName' or 'function functionName' inside of the object. Can only be accessed by other private or privileged functions.</p></li> <li><p>Public Declared with 'this.variableName' inside of the object. Can be changed by any function or method.</p></li> <li><p>Privileged Declared with 'this.functionName = function(){ ... }' inside of the object. Can be accessed by any function or method and can call reference or change any Private variable.</p></li> <li><p>Prototype Declare with 'Class.prototype.variableName' or 'Class.prototype.functionName'. Functions declared this way will have access to any public or prototype variables. Attempts to change variable created this way will instead create a new public variable on the object and the prototype variable will be unavailable.</p></li> <li><p>Static Declare with 'Class.variableName' or 'Class.functionName'. Can be changed by any function or method. This method is rarely used. To understand these different levels, let's look at an example:</p></li> </ul> <hr> <pre><code>function Cat(name, color){ /* Constructor: any code in here is run when the object is created */ Cat.cats++; /* Private variables and functions - may only be accessed by private or privileged functions. Note that 'name' and 'color', passed into the Class, are already private variables. */ var age = 0; var legs = 4; function growOlder(){ age++; } /* Public variables - may be accessed publicly or privately */ this.weight = 1; this.length = 5; /* Privileged functions - may be accessed publicly or privately May access Private variables. Can NOT be changed, only replaced with public versions */ this.age = function(){ if(age==0) this.length+=20; growOlder(); this.weight++; } } /* Prototyped Functions - may be accessed publicly */ Cat.prototype = { talk: function(){ alert('Meow!'); }, callOver: function(){ alert(this.name+' ignores you'); }, pet: function(){ alert('Pet!'); } } /* Prototyped Variables - may be accessed publicly. May not be overridden, only replaced with a public version */ Cat.prototype.species = 'Cat'; /* Static variables and functions - may be accessed publicly */ Cat.cats = 0; </code></pre>
 

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