javascript - 原型(prototype)方法可以访问构造函数的上下文(闭包)

标签 javascript

考虑以下代码:

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个 不明确的 11

为了保持代码阅读简单,我更喜欢将方法添加到原型(prototype),如 countBranches(),而不是像 countFruits() 这样的内部构造函数。但是,缺点是原型(prototype)函数不能访问 Tree 的私有(private)变量。有办法吗?

最佳答案

However, the disadvantage is that the prototype functions can not access Tree's private variables. Is there a way to do that?

所以你想要一个不是私有(private)的私有(private)变量。不,没有办法做到这一点。任何函数都不能访问其他函数的内部状态。

但是,如果您将 smallBranches 设为私有(private)的目的是防止它被覆盖,您可以在添加访问器时将其设为私有(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
};

关于javascript - 原型(prototype)方法可以访问构造函数的上下文(闭包),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40797513/

相关文章:

JavaScript 函数不起作用

javascript - 函数的范围问题并转换为箭头函数

javascript - 以正确的布局添加自定义下拉列表(数据表插件)

javascript - ng-show 语法错误 : "token ' false' is at column {2} of the expression [{3}] starting at [{4}]"

c# - 使用 WebBrowser.Document.InvokeScript 调用 javascript 对象方法

javascript - Selectize.js:使用默认值填充

javascript - 未使用回调时函数返回未定义,使用回调时,JS 说函数未定义

javascript - 每次刷新时从内部更新面板执行 javascript

javascript - Workbox - SPA - 回退到/index.html

javascript - 即使有足够的缓冲区空间,WebGL 也无法绘制超过 44 个点