开发者

function used from within javascript dojo closure using "this"-notation is undefined

I have a Problem accessing an Object function using "this". In case of the below example (which is simplified, because I cannot supply actual code due to various reasons) the function call this._getEntry() is "undefined" when calling createList().

I would hope for some opinions on wether this is due to a misunderstanding of javascript closures or rather a syntax error.

In the latter case I will have to find the error in the actual code myself.

If it is a misunderstanding of javascript or dojo concepts I would really appreciate some help on how to correctly scope and access the below mentioned function (_getEntry()).

var OBJECT = {
  _getEntry : function(entry){
    var li = document.createElement('LI');
    li.appendChild(document.createTextNode(entry));
    return li;
  },
  createList : function(entryArray){
    var list = doc开发者_如何学JAVAument.createElement('UL');
    dojo.forEach(entryArray,function(entry){
      list.appendChild(this._getEntry(entry));
    });
    dojo.body().appendChild(list);
  }
};
OBJECT.createList(["entry1","entry2"]);

thanks!


Firstly, I think your pasted code is missing ); to complete the forEach.

Secondly, forEach takes an optional third parameter which determines the context in which the passed function runs. If not given, it defaults to the global scope, so yes this is your problem. Assuming this already refers to what you need it to immediately outside the forEach, you should be able to just pass this in as the third argument to forEach and it should work, e.g.:

dojo.forEach(entryArray, function(entry){
  list.appendChild(this._getEntry(entry));
}, this);

For more information: http://dojotoolkit.org/api/dojo/forEach - which is based on the API in JS 1.6 https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/forEach


This is a common problem and you are right, its all about scoping and closure. What is happening here is once you get into the forEach the context changes to the global context (window). Handily, Dojo provides a way to set this context:

  createList : function(entryArray){
    var list = document.createElement('UL');
    dojo.forEach(entryArray,function(entry){
      list.appendChild(this._getEntry(entry));
    }, this);

    dojo.body().appendChild(list);
  }

An alternate approach is to use closure to get at this

  createList : function(entryArray){
    var list = document.createElement('UL');
    var _this = this; // closure allowing the forEach callback access to this
                      // some popular variable names used for this include:
                      // $this, _this, me and that
    dojo.forEach(entryArray,function(entry){
      list.appendChild(_this._getEntry(entry));
    });

    dojo.body().appendChild(list);
  }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜