如何用这种模式定义内联getter

How to define inline getter with this pattern?

本文关键字:getter 定义 模式 何用这      更新时间:2023-09-26

我正试图将股权属性内联并与语法有问题。用这种模式定义内联getter属性的正确方法是什么?

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

Account构造函数中:

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

尽管,说实话,你在上面想做什么并不清楚。

这有什么不对?

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