Search code examples
javascriptprivate-methods

Access a member variable from a private method in JavaScript


lick() is a private method of Cat. Unfortunately, Cat's this.paw is not accessible in lick(). Is there a simple way to create a private method that has access to the member variables of its containing class?

<!doctype html>
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<p id="catStatus">???</p>
<script>
function Cat() {

    this.paw;

    var lick = function() {
        alert(this.paw);
        if(this.paw == "sticky") {
            alert("meow");
            document.getElementById("catStatus").innerHTML = "*Slurp*";
        }
    };

    this.beCat = function() {
        this.paw = "sticky";
        lick();
    }
}
var kitty = new Cat();
kitty.beCat();
</script>
</body>
</html>

Result


Solution

  • The value of this depends on how you call the method.
    Since you're not calling the method on the object instance, this becomes the global object.

    Instead, you need to save this in a variable:

    function Cat() {
        this.paw = ...;
    
        var me = this;
    
        var lick = function() {
            alert(me.paw);
            if(me.paw == "sticky") {
                alert("meow");
                document.getElementById("catStatus").innerHTML = "*Slurp*";
            }
        };
    
        this.beCat = function() {
            this.paw = "sticky";
            lick();
        }
    }