0

I'm trying to move the Equity property inline and having trouble with the syntax. What is the correct way to define inline getter properties with this pattern?

Account = function() {
  var Number;
  var Cash;
  var MTMPL;

  function Account(number, cash, mtmpl) {
    this.Number = number;
    this.Cash = cash;
    this.MTMPL = mtmpl;
  };

  // How to define the Equity property inline?  
  Account.prototype.Equity = {
    get: function() {
      return this.Cash + this.MTMPL;
    }
  }

  return Account;
}();

var account = new Account("123", 100, 50);

/*
Object.defineProperties(Account.prototype, {
Equity : {
        get : function() {
            return this.Cash + this.MTMPL;
        }
    }
});*/

alert(account.Equity);
Mr. Polywhirl
  • 42,981
  • 12
  • 84
  • 132
ddrjca
  • 472
  • 2
  • 15
  • (Opinion) You don't it makes it harder to read. Also this is primarily opinion based, you can code how ever works best for you and your team. – Ryan Aug 27 '15 at 17:36
  • I didn't do much, but just some cleanup and removed unnecessary code and [here is the result](http://ideone.com/adWJWL) – thefourtheye Aug 27 '15 at 17:37

2 Answers2

2

Within the Account constructor:

Object.defineProperty(this, 'Equity', {
    get: function() { return this.Cash + this.MTMPL; }
});

Even though, to be honest, it's not clear what you are trying to do above.

skypjack
  • 49,335
  • 19
  • 95
  • 187
  • @ddrjca: Add the definition for the equity field to the constructor of the Account object. Also, fields for OOP should be lowercase to reduce confusion between class/object type names. http://jsfiddle.net/MrPolywhirl/9onh5kyh/ – Mr. Polywhirl Aug 27 '15 at 17:45
  • Does this particular pattern have a name ? It would be helpful to know for when I research future questions. The way I defined the Account object. – ddrjca Aug 27 '15 at 17:56
0

What is wrong with this?

Account =  function () {
    var Number;
    var Cash;
    var MTMPL;

    function Account(number,cash,mtmpl) {
        this.Number = number;
        this.Cash = cash;
        this.MTMPL = mtmpl;
    };

    Object.defineProperties(Account.prototype, {
        Equity : {
            get : function() {
                return this.Cash + this.MTMPL;
            }
        }
    });
    return Account;
}();
var account = new Account("123",100,50);
alert(account.Equity);
Tamas Hegedus
  • 28,755
  • 12
  • 63
  • 97