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

时间:2016-11-25 04:00:48

标签: javascript

请考虑以下代码:

create table customer parallel 2 nologging as 
select /*+parallel(source 4) */ *  mk.num,
 nm.id_prefix||substr(mk.subid,6) new_sub_id,
 nm.id_prefix||substr(mk.custid,6) new_cust_id
 from user_info mk,numbersegment nm where mk.num >=nm.startnum and mk.num    <=nm.endnum;

输出是: 五 未定义 11

为了简化代码阅读,我更喜欢将方法添加到原型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(); 而不是像countBranches()这样的内部构造函数。但是,缺点是原型函数无法访问Tree的私有变量。有没有办法做到这一点?

2 个答案:

答案 0 :(得分:5)

  

但是,缺点是原型函数无法访问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,请将其设为仅包含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
};

答案 1 :(得分:0)

实际上,通过原型,外部构造函数关联成员函数的方法是将成员函数添加到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);
  };

};
相关问题