Accessing Private Member Variables from Prototype-Defined Functions
In JavaScript, private member variables, defined within the constructor, are inaccessible to prototype-defined methods. This is evident in the following code snippet:
TestClass = function(){ var privateField = "hello"; this.nonProtoHello = function(){alert(privateField)}; }; TestClass.prototype.prototypeHello = function(){alert(privateField)};
While nonProtoHello successfully accesses privateField, prototypeHello fails.
Reasoning
Functions, including prototype-defined methods, have access to the scope in which they are defined. Private member variables are defined within the constructor scope, making them inaccessible to prototype-defined methods.
Solution
To provide prototype methods access to private variables:
For example:
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()); };
This approach allows prototype-defined methods to interact with private member variables through getters and setters, while maintaining encapsulation.
The above is the detailed content of How to Access Private Member Variables from Prototype-Defined Functions in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!