Can use a prototype of a method access to a constructor function (closure)

Consider the following code:

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

Output: 5 undefined 11

To make code easier to read, I prefer to add methods to the type prototype countBranches()instead of internal build functions such as countFruits(). However, the disadvantage is that prototype functions cannot access Tree private variables. Is there any way to do this?

+4
source share
2 answers

However, the disadvantage is that prototype functions cannot access Tree private variables. Is there any way to do this?

, , . , . .

, smallBranches private - , :

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, 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
};
+5

- , - - javascript. undefined - 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);
  };

};
0

Source: https://habr.com/ru/post/1661900/


All Articles