Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/spring-mvc/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript中结束的细微差别_Javascript_Functional Programming_Closures_Lexical Closures - Fatal编程技术网

Javascript中结束的细微差别

Javascript中结束的细微差别,javascript,functional-programming,closures,lexical-closures,Javascript,Functional Programming,Closures,Lexical Closures,我一直在努力理解Javascript的功能组合技术,我提出了一个玩具准MVC的工作代码来演示我的问题: var modelFactory=function(){ var_state=false; var_listener=null; var_updateView=函数(){ _侦听器(_状态); }; 变量_接口={ registerListener:函数(侦听){ _聆听者=倾听; }, eventHandler:function(){ _状态=真; _updateView(); } };

我一直在努力理解Javascript的功能组合技术,我提出了一个玩具准MVC的工作代码来演示我的问题:

var modelFactory=function(){
var_state=false;
var_listener=null;
var_updateView=函数(){
_侦听器(_状态);
};
变量_接口={
registerListener:函数(侦听){
_聆听者=倾听;
},
eventHandler:function(){
_状态=真;
_updateView();
}
};
返回接口;
};
var viewFactory=function(updateFunction){
var_hook=$('');
$('body')。追加(_hook);
变量_接口={
getHook:函数getHook(){
回程钩;
},
更新:updateFunction(_hook)
};
返回接口;
};
var main=函数(){
var modelInstance=modelFactory();
var viewInstance=viewFactory(
函数bindHook(hook){
返回函数bindState(state){
如果(状态===true){
hook.addClass(“红色”);
}否则{
hook.removeClass(“红色”);
}
};
}
);
registerListener(viewInstance.update);
modelInstance.eventHandler();//调用时,改变_状态,然后调用侦听器
};
$(文件).ready(主)
.box{
背景色:#000;
宽度:100px;
高度:100px;
}
瑞德先生{
背景色:#f00;
}

我想您只是想将闭包的创建放在您的
视图工厂中

function viewFactory(updateFunction) {
  var _hook = $('<div class="box"></div>');
  return {
    getHook: function getHook() {
      return _hook;
    },
    update: function(state) {
      return updateFunction(_hook, state)
    }
  };
}

…
var viewInstance = viewFactory(function bindState(hook, state) {
  hook[state ? "addClass" : "removeClass"]("red");
});
$('body').append(viewInstance.getHook());
modelInstance.registerListener(viewInstance.update);
或者只是(等价地)


好极了有人不厌其烦地构造了一个半途而废的问题。对不起,你在说什么“挂起”变量?对不起!我是说胡克。这个例子来自一个在钩子上使用挂起方法的程序。我把他们弄糊涂了——编辑很快。编辑是为了纠正这个错误命名。
update: function(state) {
  return updateFunction.call(_hook, state); // notice the similarity to above
}
update: updateFunction.bind(_hook)