JavaScript Classes

前端 未结 8 472
心在旅途
心在旅途 2020-12-07 09:21

I understand basic JavaScript pseudo-classes:

function Foo(bar) {
    this._bar = bar;
}

Foo.prototype.getBar = function() {
    return this._bar;
};

var f         


        
8条回答
  •  死守一世寂寞
    2020-12-07 10:13

    One problem with a lot of JS classes out there is that they do not secure their fields and methods which means that anyone using it may accidentally replace a method. For example the code:

    function Class(){
        var name="Luis";
        var lName="Potter";
    }
    
    Class.prototype.changeName=function(){
        this.name="BOSS";
        console.log(this.name);
    };
    
    var test= new Class();
    console.log(test.name);
    test.name="ugly";
    console.log(test.name);
    test.changeName();
    test.changeName=function(){
        console.log("replaced");
    };
    test.changeName();
    test.changeName();
    

    will output:

    ugly
    BOSS
    replaced 
    replaced 
    

    As you can see the changeName function gets overriden. The following code would secure the class methods and fields and the getters and setters would be used to access them making this more of a "regular" class found in other languages.

    function Class(){
        var name="Luis";
        var lName="Potter";
    
        function getName(){
             console.log("called getter"); 
             return name;
        };
    
        function setName(val){
             console.log("called setter"); 
             name = val
        };
    
        function getLName(){
             return lName
        };
    
        function setLName(val){
            lName = val;
        };
    
        Object.defineProperties(this,{
            name:{
                get:getName, 
                set:setName, 
                enumerable:true, 
                configurable:false
            },
            lastName:{
                get:getLName, 
                set:setLName, 
                enumerable:true, 
                configurable:false
            }
        });
    }
    
    Class.prototype.changeName=function(){
        this.name="BOSS";
    };   
    
    Object.defineProperty(Class.prototype, "changeName", {
        writable:false, 
        configurable:false
    });
    
    var test= new Class();
    console.log(test.name);
    test.name="ugly";
    console.log(test.name);
    test.changeName();
    test.changeName=function(){
        console.log("replaced")
    };
    test.changeName();
    test.changeName();
    

    This outputs:

    called getter
    Luis
    called setter 
    called getter 
    ugly 
    called setter 
    called setter 
    called setter 
    

    Now your class methods cannot be replaced by random values or functions and the code in the getters and setters always run when attempting to read or write to field.

提交回复
热议问题