使用闭包创建的私有函数如何访问构造函数中定义的变量

How private function created with closure can access variable defined in constructor?

本文关键字:访问 构造函数 定义 变量 创建 闭包 函数 何访问      更新时间:2023-09-26

我有以下代码:

var TagCloud = (function() {
  var createTagsArray = function() {
    j$("#" + this.cloudId + " a").each(function(index) {
      //bla bla
    });
  }
  function TagCloud(cloudId) {
    this.cloudId = cloudId;
  };
  TagCloud.prototype.createTagCloud = function(){
    createTagsArray(this.cloudId);            
  };
  return TagCloud;
}());
new TagCloud("tagcloud");

我创建TagCloud对象。我用闭包创建它,以具有一个私有函数createTagArray。然而,在这个函数中,我可以访问TagCloud构造函数-cloudId中定义的变量。当然,在这个例子中,我无法使用this获得它。但有没有办法得到它?(我不想将此值作为函数createTagArray参数传递)。

这也可能是我理解闭包用法的错误,因为我已经开始处理闭包了。

您不能通过闭包访问变量,因为您需要在TagCloud构造函数中定义createTagsArray函数,然后如果不将其公开,就不能再从createTagCloud方法访问它。

但我认为你无论如何都不想访问这个变量。您想要访问实例的.cloudId属性,为此您需要该实例。

实际上,最好将其作为参数传递——属性值或完整实例。这没什么错:

var createTagsArray = function(cloudId) {
  j$("#" + cloudId + " a").each(function(index) {
    //bla bla
  });
}
TagCloud.prototype.createTagCloud = function(){
  createTagsArray(this.cloudId);
};

使用call,您甚至可以传递实例本身,以便可以作为this:访问它

var createTagsArray = function() {
  j$("#" + this.cloudId + " a").each(function(index) {
    //bla bla
  });
}
TagCloud.prototype.createTagCloud = function(){
  createTagsArray.call(this);
};

从那里你甚至可以很容易地切换(来回)到半私有方法:

TagCloud.prototype._createTagsArray = function() {
  j$("#" + this.cloudId + " a").each(function(index) {
    //bla bla
  });
}
TagCloud.prototype.createTagCloud = function(){
  this._createTagsArray();
};

尝试以下代码:

function TagCloud(cloudId) {
  var self = this;
  self.createTagsArray = function() {
    console.log(this);
  }
  self.cloudId = cloudId;
  self.createTagCloud = function() {
    self.createTagsArray()
  }
  
  return{
    "cloudId": cloudId,
    "createTagCloud": self.createTagCloud
  }
};
var obj = new TagCloud("tagcloud");
obj.createTagCloud();
var obj = new TagCloud("TagCloudTest");
obj.createTagCloud();