Vue.js v2.1.10 源码探索 v1.1.0

    xiaoxiao2021-03-25  84

    Remerber to keep it Simple,Stupid.Do one thing and do it best.

    精髓 cached( )

    /** * Create a cached version of a pure function. * 创建一个纯函数的缓存版本。 */ function cached(fn) { //首先创建一个没有原型的缓存对象 var cache = Object.create(null); return (function cachedFn(str) { // 缓存传入的键值 str var value = cache[ str ]; return (value ? value || cache[ str ] = fn(str) }) }

    分析1

    function cached(fn) { // 稍微改造下 为了更好的理解 var fn = fn; //首先创建一个没有原型的缓存对象 var cache = Object.create(null); return (function cachedFn(str) { // 缓存传入的键值 str var value = cache[ str ]; console.log(cache, value); // 为了更好的理解 return (value ? value || cache[ str ] = fn(str) }) } /** * Camelize a hyphen-delimited string. * 骆驼化以连字符分隔的字符串 */ //命名的细节 RegExp var camelizeRE = /-(\w)/g; var camelize = cached(function (str) { return str.replace( camelizeRE, function ( _, c){ c ? c.toUpperCase(): '';) });

    cached( )里发生了什么

    首先返回了 cachedFn( )目的是建一个闭包, 保存了匿名函数 function ( str ) 即 fn 和 缓存对象 cache = { };

    接着是让索引 var camelize 指向了闭包function cachedFn( ) 这样垃圾清理机制 就不会清除保存的数据了

    好了测试下这个 camelize

    camelize('-w') // 缓存的键值对 {-w: "W"} 函数的返回值 "W"

    当第一次执行camelize( ) 时 实际是执行了将 (cache[ ‘-w’ ] = ‘W’ ); 最后返回了‘W’;

    转载请注明原文地址: https://ju.6miu.com/read-14887.html

    最新回复(0)