Home > Web Front-end > JS Tutorial > body text

How Can I Access Private Members from Prototype-Defined Functions in JavaScript?

Patricia Arquette
Release: 2024-10-29 00:07:30
Original
835 people have browsed it

How Can I Access Private Members from Prototype-Defined Functions in JavaScript?

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>
Copy after login

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>
Copy after login

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!

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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!