0

Is there any way to force a prototype's method (function) to be a property?

Say I have Foo with the method bar:

Foo.prototype.bar = function getBar() {
    return something
}

To call bar, I can simply call foo.bar();, However I want bar to be a property of Foo, not a method, meaning foo.bar;. To do so, I can simply make getbar() a self invoking function:

Foo.prototype.bar = (function getBar() {
    return something
})();

Now .bar is callable as a property. BUT the problem is that bar is only set when an instance of Foo is created, not every time .bar is called.

Is there any way I can get getBar() to be executed every time I call foo.bar?

samd
  • 25
  • 7

1 Answers1

1

You can do that using a getter:

function Foo () {
    this.x = 1;
};

// Example of adding a getter to Foo.prototype
Object.defineProperty(Foo.prototype, 'bar', {
  get: function getBar () {
    return this.x++;
  }
});

var tmp = new Foo;

tmp.bar; // 1
tmp.bar; // 2
tmp.bar; // 3
Paul
  • 139,544
  • 27
  • 275
  • 264