Skip to main content
Inspiring
January 31, 2017
Question

Implicit setters and getters

  • January 31, 2017
  • 1 reply
  • 311 views

Hi

This might be more a javascript syntax question, but here goes:

I create a object def like this:

function MyObjectDef()

{

    this.initialize();

};

MyObjectDef.prototype.initialize = function()

{

    this.a = 10;

}

var mo = new MyObjectDef();

alert(mo.a);

Question is, how do I create an implicit setter for that object? I know I could do this:

MyObjectDef.prototype.setA = function(v)

{

    this.a = v*2;

}

mo.setA(10);

alert(mo.a); // would return 20

But I would much prefer something like this (which obviously doesn't work):

MyObjectDef.prototype.set a = function(v)

{

    this.a = v*2;

}

mo.a = 10;

alert(mo.a); // would return 20

Any help?

Thanks,

Jakob

This topic has been closed for replies.

1 reply

Participant
March 14, 2024
  1. Encapsulation Principle: Implicit setters and getters are a fundamental aspect of encapsulation in object-oriented programming.
  2. Access Control: They provide controlled access to class properties, allowing manipulation within defined boundaries.
  3. Data Abstraction: Setters and getters abstract the underlying data representation, shielding the implementation details from external entities.
  4. Encapsulation Integrity: By enforcing access through setters and getters, encapsulation ensures data integrity and prevents direct manipulation.
  5. Consistency: Implicit setters and getters promote uniform access to class properties, enhancing code consistency and maintainability.
  6. Validation: Setters enable validation logic to be applied to gas before modifying property values, ensuring data integrity.
  7. Flexibility: They allow for future enhancements or modifications to the class's internal representation without affecting external code.
  8. Encapsulation Boundary: Setters and getters define a clear boundary between the internal state of an object and its external interface.
  9. Documentation: They serve as documentation points, revealing the intended usage and behavior of class properties.
  10. Encapsulation Compliance: Adherence to the principle of encapsulation through setters and getters fosters code that is easier to understand and extend.
  11. Property Access Control: Setters and getters enable fine-grained control over property access, facilitating implementation-specific logic.
  12. Gas Analogy: Implicit setters and getters act as valves regulating the flow of data, akin to controlling the flow of gas in a system, ensuring smooth operation and preventing leaks.