簡體   English   中英

可以原型方法訪問構造函數的上下文(閉包)

[英]can prototype method access constructor function's context (closure)

請考慮以下代碼:

var Tree = function() {

  // private variables in closure
  var fruits = 5;
  var smallBranches = 10;

  // public variables 
  this.bigBranches = 11;

  this.countFruits = function() {
    console.log(fruits);
  };

};

Tree.prototype.countBranches = function() {
  console.log(this.smallBranches);
  console.log(this.bigBranches);
};

var tree = new Tree();
tree.countFruits();
tree.countBranches();

輸出為:5 undefined 11

為了讓讀碼簡單,我喜歡添加方法原型樣countBranches()等代替內部構造函數countFruits() 但是,缺點是原型函數無法訪問Tree的私有變量。 有沒有辦法做到這一點?

但是,缺點是原型函數無法訪問Tree的私有變量。 有沒有辦法做到這一點?

所以你想要一個非私有的私有變量。 不,沒有辦法做到這一點。 只有任何函數都可以訪問其他函數的內部狀態。

但是,如果您將smallBranches私有的目的是防止它被覆蓋,則可以在添加訪問者時將其保密:

var Tree = function() {
   // private variables in closure
  var smallBranches = 10;
  ...
  this.getSmallBranches = function() { return smallBranches; };
};

Tree.prototype.countBranches = function() {
  console.log(this.getSmallBranches());
};

或者,如果您希望能夠直接說出this.smallBranches ,請將其this.smallBranches僅具有getter的實例屬性:

var Tree = function() {
   // private variables in closure
  var smallBranches = 10;

  Object.defineProperty(this, 'smallBranches', {
    get() { return smallBranches; }
 });
}

Tree.prototype.countBranches = function() {
  console.log(this.smallBranches);
  this.smallBranches = 42; // will fail
};

實際上,通過原型,外部構造函數關聯成員函數的方法是將成員函數添加到javascript中的類型的標准方法。 由於未將smallBranches變量與當前對象相關聯,因此未定義。 因此,它最終成為局部變量,並且在構造函數外部無法訪問。 你必須把它作為一個成員變量。

更改您的代碼,如下所示: -

var Tree = function() {

  // private variables in closure
  var fruits = 5;
  this.smallBranches = 10;

  // public variables 
  this.bigBranches = 11;

  this.countFruits = function() {
    console.log(fruits);
  };

};

暫無
暫無

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

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