簡體   English   中英

用閉包創建的私有函數如何訪問構造函數中定義的變量?

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

我有以下代碼:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM