如何访问外部函数的参数'parent'??? 请在代码中查看评论
!!
上次编辑:这个问题有误导性,我的问题是由错误的输入参数引起的
renderData : function(parent, children){
children.each(function(e, index){
var li = new Element('li');
var hasChildren = false;
if(e.children && e.children.length >0){
var img = new Element('img');
img.src = 'a1.png';
img.inject(li);
hasChildren = true;
}
if(e.icon){
var img = new Element('img');
img.src = e.icon;
img.inject(li);
}else{
var img = new Element('img');
img.src = 'b1.png';
img.inject(li);
}
li.set('html',e.text);
console.log(this);
// how to access outer function's argument 'parent' ???
li.inject(parent);
if(hasChildren){
var ul = new Element('ul');
this.renderData(ul, e.childRen);
ul.inject(e);
}
}.bind(this));
答案 0 :(得分:1)
在每个循环中:
array.each(function(el) {
this.method(); // this == (instance / scope)
}, this); // where **this** is your parent scope.
另一种可接受的方式是:
var self = this;
...
array.each(function(el) {
self.method(); // fine.
}); // where this is your parent scope.
http://mootools.net/docs/core/Types/Array#Array:Array-each
虽然使用.bind(this)
也应该有效... http://www.jsfiddle.net/dimitar/fFy4J/ - 那么问题是什么?
答案 1 :(得分:1)
如果我理解正确,你的问题就是你不能li.inject(parent)
没有理由不能访问'parent',因为它已作为参数传递给函数renderData()
我试过这个simple test
var test;
window.addEvent('domready', function(){
test = new TestClass();
});
var TestClass = new Class({
Implements: [Options, Events],
initialize: function(){
this.renderData($('parent'),$$('span'))
},
renderData : function(parent, children){
children.each(function(e, index){
console.log(parent);
}.bind(this));
}
});
它工作正常......但我不确定你的代码有什么问题