1

In the code below I have defined Greeter.prototype.isVeryPolite = function () {... for accessing this._isVeryPolite with

greeter.isVeryPolite()

but the "()" at the end is not very user friendly. Is there a trick in javascript to be able to have greeter.isVeryPolite without accessing a member directly ?

https://jsfiddle.net/5r4so2Ld/

var Greeter = (function () {
    function Greeter(message, flag) {
        this._name = message;
        this._isVeryPolite = flag;
    }
    Greeter.prototype.greet = function () {
        if (this._isVeryPolite) {
            return "How do you do, " + this._name;
        }
        else {
            return "Hello " + this._name;
        }
    };
    Greeter.prototype.isVeryPolite = function () {
        return this._isVeryPolite;
    };
    return Greeter;
})();
var greeter = new Greeter("world", true);
var button = document.createElement('button');
button.textContent = "Say Hello";
button.onclick = function () {
    alert(greeter.greet());
    alert(greeter.isVeryPolite());
};
document.body.appendChild(button);
user310291
  • 36,946
  • 82
  • 271
  • 487
  • The `()` denotes a function call, without it you just refer to a property. Why do you want to omit that? What's the benefit? – k0pernikus Feb 08 '16 at 22:01
  • You can define a getter (as long as you don't need to support old browsers), but your `_isVeryPolite` property *is* public... – nnnnnn Feb 08 '16 at 22:05

3 Answers3

7

It sounds like you're looking for a getter. An example (taken from MDN):

var log = ['test'];
var obj = {
  get latest () {
    if (log.length == 0) return undefined;
    return log[log.length - 1]
  }
}
console.log (obj.latest); // Will return "test".
Seiyria
  • 2,112
  • 3
  • 25
  • 51
3

You can use the Object.defineProperty method to define a getter:

    Object.defineProperty(Greeter.prototype, "isVeryPolite", 
    {
       get: function() {return this._isVeryPolite; },
    });
Mark Cidade
  • 98,437
  • 31
  • 224
  • 236
2

You can use the Object.defineProperty to stay with your prototype pattern and still use the getter pattern.

Object.defineProperty(Greeter.prototype, "isVeryPolite", {
    get: function isVeryPolite() {
        return this.isVeryPolite;
    }
});
Victory
  • 5,811
  • 2
  • 26
  • 45