Home > Web Front-end > JS Tutorial > How to Access Private Member Variables from Prototype-Defined Functions in JavaScript?

How to Access Private Member Variables from Prototype-Defined Functions in JavaScript?

Susan Sarandon
Release: 2024-10-26 14:10:30
Original
523 people have browsed it

How to Access Private Member Variables from Prototype-Defined Functions in JavaScript?

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)};
Copy after login

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:

  • Define getters and setters on the this object.
  • Prototype methods can access these getters and setters to interact with the 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()); };
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template