SoFunction
Updated on 2025-02-28

How to implement private attribute writing method in JavaScript (I)

I have discussed the way of writing classes in JavaScript before. But no private implementation is discussed. Read this article.

We know that the essence of implementation of private attributes in JS is var + closure. as follows

Copy the codeThe code is as follows:

function Person(n, a){
    // public
    = n;
    // private
    var age = a;
    = function(){
        return ;
    }
    = function(){
        return age;
    }
}

The test is as follows: age is private and cannot be obtained using the dot operator, but can only use the getName method.
Copy the codeThe code is as follows:

var p = new Person('jack',23);
();  // undefined
(()); // 23

There is nothing strange about the above, let's use a tool function to implement it.
Copy the codeThe code is as follows:

/**
 * @param {String} className
 * @param {Function} classImp
 */
function $class(className, classImp){
    function clazz(){
        if(typeof == "function"){
            (this, arguments);
        }
    }
    ();
    window[className] = clazz;
}

Write a class
Copy the codeThe code is as follows:

$class('Person', function(){
// All private attributes are defined here
    var age = '';
    = function(n, a){
// The common attributes are hung on this and initialized
        = n;
// Private attribute initialization
        age = a;
    };
    = function(){
        return ;
    };
    = function(){
        return age;
    }
});

new an instance object
Copy the codeThe code is as follows:

var p = new Person('jack',23);
(); // jack can be obtained using dot operators
(); // undefined private cannot be obtained through dot operators
(()); // 23 Private age can only be obtained through the common method getAge