Js uses closures to simulate private variables

function Ninja(){
    var feints = 0;
    this.getFeints = function(){
        return feints;
    };
    this.feint = function() {
        feintsPP;
    };
}
var ninja1 = new Ninja();
ninja1.feint();
console.log(ninja1.feints);
console.log(ninja1.getFeints());
    

/ / undefined
/ / 1
I would like to ask how the closure here can get the value of the accumulated feints through ninja1.getFeints (), but not directly through ninja1.feints?

can it be understood that ninja1.feints cannot be accessed because feints is inside the constructor, but by calling the method ninja1.feint (), feints exists in the closure, so it can be returned through getFeints ()?

Mar.14,2021

question 1: console.log (ninja1.feints). The ninja1 object does not have a feints attribute, so print undefind;
question 2: the scope of the fients variable is Ninja, which can be accessed within the object. As for the function return, it is only the returned data.

Menu