
Accessing Private Member Variables from Prototype-Defined Functions
In JavaScript, when defining methods inside the constructor of a class, you can access private variables declared within the constructor. However, when defining methods on the prototype, accessing these private variables becomes problematic.
To illustrate:
<code class="js">function TestClass() {
var privateField = "hello";
this.nonProtoHello = function() { alert(privateField); };
}
TestClass.prototype.prototypeHello = function() { alert(privateField); };</code>Calling t.nonProtoHello() correctly accesses the private privateField, but t.prototypeHello() throws an error. This is because prototype-defined methods are not defined within the constructor's scope, and thus cannot access its local variables.
Unfortunately, there is no way to directly access private variables from prototype-defined functions. However, you can achieve similar functionality using getters and setters.
<code class="js">function Person(name, secret) {
// Public
this.name = name;
// Private
var secret = secret;
// Public methods have access to private members
this.setSecret = function(s) {
secret = s;
}
this.getSecret = function() {
return secret;
}
}
// Must use getters/setters
Person.prototype.spillSecret = function() { alert(this.getSecret()); };</code>In this example, the private variable secret is accessible to prototype-defined methods via the getter and setter functions.
The above is the detailed content of How Can I Access Private Members from Prototype-Defined Functions in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!