Stanislav Zorjan - Stasha - Full Stack Software Engineer and Game Development Hobbyist - Prague


JavaScript OOP - Classes & Objects
JavaScript OOP - Methods & Properties
JavaScript OOP - Getters & Setters
JavaScript OOP - Encapsulation
JavaScript OOP - Inheritance

 

JavaScript OOP - Getters and Setters

 


function SomeClass(){
    
    // private properties (fields)
    var firstName = "";
    var lastName = "";

    //This type of getters and setters doesn't work in any IE
    this.__defineGetter__("firstName", function(){
        return firstName;
    });

    this.__defineSetter__("firstName", function(value){
        firstName = value;
    })

    this.__defineGetter__("lastName", function(){
        return lastName;
    });

    this.__defineSetter__("lastName", function(value){
        lastName = value;
    })
}

function SomeClass2(){
    
    // private properties (fields)
    var firstName = "";
    var lastName = "";
    
    // Java style getters and setters. 
    this.setFirstName = function(value){
        firstName = value;
    }
    
    this.getFirstName = function(){
        return firstName;
    }
    
    this.setLastName = function(value){
        lastName = value;
    }
    
    this.getLastname = function(){
        return lastName;
    }
}

/*var sc = new SomeClass();
sc.firstName = "Stanislav";
sc.lastName = "Zorjan";*/

var sc2 = new SomeClass2();
sc2.setFirstName("Stanislav");
sc2.setLastName("Zorjan");

//alert(sc.firstName+", "+sc.lastName+", "
+sc2.getFirstName()+", "+sc2.getLastname());
alert(sc2.getFirstName()+", "+sc2.getLastname());