簡體   English   中英

Javascript模擬真實的私有變量並使用getter / setter對其進行管理

[英]Javascript simulate real private variable and manage it with getter/setter

我可以通過這種方式正確使用私有變量的模擬嗎?

var C = function(a) {
    var _private = a + 1;
    // more code...
    Object.defineProperties(this, {
        'privateProp': {
            get: function() {
                return _private;
            },
            set: function(b) {
                _private = b + 2;
            }
        }
    });
}

因此,使用getter / setter可以管理該私有變量。 它的值可以使用自定義方法獲取/設置。

假設這個例子

var c = new C(5);

console.log(c.privateProp); // 6
c.privateProp = 2;
console.log(c.privateProp); // 4

沒有模擬私有變量的正確方法,因為它們不是Javascript規范的一部分。

但是,仍然有許多方法可以模擬它們:

與吸氣劑和二傳手

這與您的答案相同,但語法略有不同:

function Rocket() {
  var _fuel = 100;

  return {
    get fuel() {
      return _fuel;
    }
    set fuel(value) {
      _fuel = value;
    }
  };
}

該語法允許您以更自然的方式定義getter和setter函數,但存在限制,即它們必須位於對象文字中。

封閉式

function Rocket() {
  var fuel = 100;

  return {
    getFuel: function() { return fuel; },
    setFuel: function(value) { fuel = value; }
  };
}

可以說這是最優雅的方式,因為自從將匿名函數添加到規范以來,這就是Java的工作方式。

按照慣例

function Rocket() {
  this._fuel = 100;

  this.getFuel = function() {
    return this._fuel;
  };

  this.setFuel = function(value) {
    this._fuel = value;
  };
}

最后一種方法是將變量公開,但在名稱開頭使用下划線將其標記為私有。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM