user310291 February 2016

isFlag instead of isFlag() syntax : is it possible in Javascript

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);

Answers


Seiyria February 2016

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".


Victory February 2016

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;
    }
});


Mark Cidade February 2016

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

    Object.defineProperty(Greeter.prototype, "isVeryPolite", 
    {
       get: function() {return this._isVeryPolite; },
    });

Post Status

Asked in February 2016
Viewed 2,305 times
Voted 5
Answered 3 times

Search




Leave an answer