Getters & Setters

Due to the nature of how object referencing works in JavaScript, JOII needs to work with two different scope objects for class definitions. One for the inside scope of the class and one for the outside (public) scope. To tackle this issue, JOII automatically generates getter and setter methods for you, provided if the associated property is declared protected or public and you didn't write any of these methods yourself. It is also considered being a good practice to use getters and setters for properties, especially when they are exposed to the public.

Because JOII basically forces you to use getters and setters, this also makes type-checking possible in the setter methods. JOII does this automatically for you in the generated methods. JOII does not overwrite existing getter and setter methods.

If a method with the same name doesn't exist yet, JOII generates:

  • a Getter method if the property is declared public or protected
  • a Setter method if the property is not declared immutable.

For more information about these rules, check out the visibility and types sections.

Public properties

var MyClass = Class({
    'public string my_string' : 'A string!',

    'public myFunction(string)' : function (value) {
        // Setters work here as well.
        this.setMyString(value);
    }
});

var mc = new MyClass();

mc.my_string;     // undefined
mc.getMyString(); // "A string!"
mc.setMyString('Hello World');
mc.myFunction('Foobar');

Protected properties

Taking the same example as above...

var MyClass = Class({
    'protected string my_string' : 'A string!',

    'public myFunction(string)' : function (value) {
        // Setters work here as well.
        this.setMyString(value);

        // Return the value
        return this.getMyString();
    }
});

var mc = new MyClass();

mc.my_string;             // undefined
mc.myFunction('Foobar');  // "Foobar"
mc.getMyString();         // Error: method getMyString is undefined.
mc.setMyString('Foobar'); // Error: method setMyString is undefined.

Private properties

Properties declared private will not have any getters or setters generated for it.

var MyClass = Class({
    'private string my_string' : 'A string!',

    'public myFunction(string)' : function (value) {
        // No setter here... Assign the value directly.
        this.my_string = value;

        // Return the value directly as well.
        return this.my_string;
    }
});

var mc = new MyClass();

mc.my_string;             // undefined
mc.myFunction('Foobar');  // "Foobar"
mc.getMyString();         // Error: method getMyString is undefined.
mc.setMyString('Foobar'); // Error: method setMyString is undefined.

Immutable properties

Properties declared immutable will not get a generated setter method, making them read-only from the outside (public) scope.