用过Prototype的人都知道,里面有个类叫做Template,用法示例如下: 复制代码 代码如下: var str = "#{what} may have gone, but there is a time of #{how}"; var object = { what : "Swallows", how : "return" } var template_1 = new Template(str); var result = template_1.evaluate(object);
console.log("result:",result); //输出:"Swallows may have gone, but there is a time of return"
这么挺方便的,所以下面就简单的分析一下实现原理,也算是源码解读的一个笔记。
我们先看一下一般需求里面会用到的一些情况,还是用上面的例子,先决定我们的形式,替换的部分是形如#{what}的内容,其中what是一个object对象的一个关键字。 现在有个问题就是,如果object是一个嵌套的对象,我们该怎么替换? 即: 复制代码 代码如下: <script type="text/javascript"> var object = { what : { name : "Swallows" }, how : "return" } </script>
所以最开始的例子可以写作: 复制代码 代码如下: <script type="text/javascript"> var str = "#{what.name} may have gone, but there is a time of #{how}"; //或者str = "#{what[name]} may have gone, but there is a time of #{how}"; var object = { what : { name : "Swallows" }, how : "return" } var template_1 = new Template(str); var result = template_1.evaluate(object);
console.log("result:",result); //输出:"Swallows may have gone, but there is a time of return" </script>
要做替换,我们最核心的就是要有一个替换字符的方法,源码里面用的是gsub,下面给出一个gsub的最简版本: 复制代码 代码如下: <script type="text/javascript"> function gsub(str,pattern, replacement){ var result = "", source = str, match; //下面的每一次匹配都是分成三段来操作的 //相当于 $` $& $" while(source.length > 0){ match = source.match(pattern); if(match){ result += source.slice(0, match.index); result += replacement(match); source = source.slice(match.index + match[0].length); }else{ result += source; source = ""; } } return result; } </script>
这个调用方法和原理跟我前面涉及的replace类似,基本可以互换。http://www.cnblogs.com/xesam/archive/2011/12/05/2276783.html 复制代码 代码如下: <script type="text/javascript"> console.log(gsub("there is a time of #{how}",/(^|.|
|
)(#{(.*?)})/,function{ return "demo"; })) //输出there is a time ofdemo </script>