zoukankan      html  css  js  c++  java
  • 深入理解javascript之惰性函数

    问题引入

    当页面代码需要重复调用某个函数来反馈事件处理函数, 而【实现逻辑是通过多个if判断】来处理的情况下,
    可以通过惰性载入函数的方式来实现. 示例如下

    function TypeA() {}
    
    function TypeB() {}
    
    function getTypeInstance() {
    	if(condition1) {
    		return new TypeA();
    	}
    	if(condition2) {
    		return new TypeB();
    	}
    }
    

    惰性载入函数

    针对以上问题,由于每次执行的时候,if条件固定不变的情况下,执行的时候每次都是在重复检测;
    惰性载入: 表示函数执行的分支仅会运行一次

    实现方式

    根据以上的实现代码如下

    方式一
    function getTypeInstance() { 
    	if(condition1) {
    		getTypeInstance = function() {
    			return new TypeA();
    		}
    		return getTypeInstance();
    	}
    	if(condition2) {
    		getTypeInstance = function() {
    			return new TypeB();
    		}
    		return getTypeInstance();
    	}
    	...
    }
    
    方式二
    var getTypeInstanceFunc = (function(){
    	if(condition1) {
    		return function() {
    			return new TypeA();
    		}
    	}
    	if(condition2) {
    		return function() {
    			return new TypeB();
    		}
    	}
    	...
    })();
    
  • 相关阅读:
    tp.c
    trace
    一致性哈希算法
    update_dctcp_alpha
    dctcp-ns2-patch
    C++ inheritance: public, private. protected ZZ
    C++ virtual inheritance ZZ
    C++ 类对象的初始化顺序 ZZ
    C++ inheritance examples
    classifier.cc-recv() [ns2.35]
  • 原文地址:https://www.cnblogs.com/pengsn/p/12758417.html
Copyright © 2011-2022 走看看