简体   繁体   中英

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

I have the following code :

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

I create TagCloud object. I create it with closure to have a private function createTagArray . However inside this function I would have an access to variable defined in TagCloud constructor - cloudId . Of course in this example I cannot get it using this . But is there anyway to get it ? (I wouldn't like to pass this value as function createTagArray parameter).

It can be also my mistake in understanding usage of closure, because I've started working with closures.

You cannot access the variable through closure, for that you would need to define the createTagsArray function within the TagCloud constructor function - and then you couldn't access it from the createTagCloud method any more without making it public.

But I don't think you want access to the variable anyway. You want access to the .cloudId property of your instance, and for that you need the instance.

Passing it - either the property value or the complete instance - as a parameter would be preferred actually. There's nothing wrong with that:

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

And using call you could even pass the instance itself so that you can access it as this :

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

From there you could even easily switch (back and forth) to a semi-private method:

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

Try following code:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM