【问题标题】:Prive Function in JS access to variablesJS中的Prive函数访问变量
【发布时间】:2012-02-06 21:12:40
【问题描述】:

我有一个结构为

的JS函数
 function myFunc (method){
      this.type = method;
      this.border = '20';
      this.add = function(){
           // some codes
           privateFunc();
      }

      var privateFunc = function(){
           //my private function
      }
  }

问题在于,私有函数无法访问任何变量(this.type、th​​is.border)。它们没有在里面定义!为什么不?!我怎样才能在那里有一个可以访问变量的私有函数?

【问题讨论】:

  • 你是什么意思他们没有定义?什么错误。正在尝试什么?

标签: javascript private


【解决方案1】:

只是为了完整性

 function myFunc (method){ 
      this.type = method; 
      this.border = '20'; 
      // take a reference to the current object
      var self = this;
      this.add = function(){ 
           // some codes 
           privateFunc(); 
      } 

      var privateFunc = function(){ 

           //now you can access your members via self variable
           self.border = 10;
      } 
  } 

这里的线索是闭包的用法。

【讨论】:

  • +1 ahh 现在这是 OP 需要的东西^_^
【解决方案2】:

this 内部的 privateFunc 值不同(它将是全局对象,而不是实例)。

最直接的解决方案是使用.bindprivateFunc 中的this 值强制为与myFunc 中的相同:

var privateFunc = function() {
  //my private function
}.bind(this);

.bind 的垫片可用于旧版浏览器。

【讨论】:

  • 重新绑定this 的替代方法是根据您喜欢的范围在变量中重命名它。我经常在这种类型的代码中看到像var self = this 这样的行——当你需要在另一个函数中访问那个范围时,你会用self.type 等来引用它。
  • @Jon:我个人觉得这有点混乱;在我看来,使用.bind 更优雅一些。但口味不同; self的方式也已经贴出来了。
  • @pimvdb 是的,很难跟上 SO 的海报 :) 重新绑定 this 对我来说有点违反直觉,因为乍一看阅读某人的代码,我通常会接受 this始终参考手头的范围。此外,它不会更改privateFunc 中的this 关键字吗?
  • @Jon: “它不会改变this 内的privateFunc 关键字吗?” - 是的,这就是我使用它的原因。 this 是实例,而不是全局对象,因为您永远不需要像 this 这样的全局对象,所以它更安全、更容易——您可以在没有额外变量的情况下获取实例属性。但我明白你的意思。
【解决方案3】:

对我来说似乎很好

function myFunc(method) {
    this.type = method;
    this.border = '20';
    this.add = function() {
        // some codes
        privateFunc();
    }

    var privateFunc = function() {
        alert(this.type);
    }

    privateFunc();
}

myFunc('hello')

小提琴:http://jsfiddle.net/maniator/4qnaH/

【讨论】:

  • 我假设 OP 使用 new myFunc;否则会污染全局范围。
  • @pimvdb 你知道当你 assme 会发生什么:-P
猜你喜欢
  • 2016-02-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-07-11
  • 2023-03-08
  • 1970-01-01
  • 1970-01-01
  • 2018-06-08
相关资源
最近更新 更多