在下面的代码中,我想将一个驻留在父作用域上的函数的引用传递给函数"嵌套"的嵌套作用域,所以我可以从父作用域调用该函数嵌套函数。我尝试将其作为参数传递,但它不起作用。我只是在学习/搞乱嵌套的闭包,并想知道是否可以这样做。
我希望调用nested
的语法为:callme.nested()
var obj = function(val){
var access = val;
var apex = 0;
return {
callme : (function(siblyng){
var privatevar = 2;
return {
nested : function(){
privatevar++;
apex = privatevar;
return access + " " + privatevar + " " + siblyng("child");
}
}
})(this.sibling),
assess : function(){
return apex + " " + this.sibling("parent");
},
sibling : function(val){
return "returned from " + val + " scope";
}
}
}
var objref = obj(true);
console.log(objref.callme.nested());
console.log(objref.callme.nested());
console.log(objref.callme.nested());
console.log(objref.assess());
console.log(objref.sibling('global'));
答案 0 :(得分:0)
如果我理解你,你可以这样做
var obj = function(val){
var access = val;
var apex = 0;
var ret;
return (ret = {
callme : function() {
var privatevar = 2;
return {
nested : function(){
privatevar++;
apex = privatevar;
return access + " " + privatevar + " " + ret.sibling("child");
}
};
}(),
assess : function(){
return apex + " " + this.sibling("parent");
},
sibling : function(val){
return "returned from " + val + " scope";
}
});
};
var objref = obj(true);
console.log(objref.callme.nested());
console.log(objref.callme.nested());
console.log(objref.callme.nested());
console.log(objref.assess());
console.log(objref.sibling('global'));
答案 1 :(得分:0)
以下代码中的this
指向global Window
对象,因此无法找到该方法。您可以直接在this.sibling
方法中调用nested
,而无需传递它。
callme : (function(siblyng){
var privatevar = 2;
return {
nested : function(){
privatevar++;
apex = privatevar;
return access + " " + privatevar + " " + siblyng("child");
}
}
})(this.sibling),