关于expres模板引擎,Function,with
2014-05-15 09:37
204 查看
本文只是一些很零散的东西,关于js的模板引擎方面的知识。
看 Node in Action的时候,有一章关于ejs,看到这样的一个片段:
这个 locals 让我迷惑不解,因为根据资料,express只是暴露了一个settings到app.locals,并没有暴露这个locals。
后来看了ejs的部分源码,才知道这个locals存在的原因,其实ejs工作机制的缘故。
现在开始说一下背景知识。
但是,除了这种方法,还有一种更灵活的方法来创建前面的函数:
这是很多魔法的来源,它实际上代表了一种思想:用代码创造代码
没啥问题。但是,再看这个:
with里面发生了什么事情呢?其实很简单,可以这样理解上面的代码:
所谓指向对象的变量,其实就是指针而已。
看 Node in Action的时候,有一章关于ejs,看到这样的一个片段:
<% if (locals.messages) { %> 后面省略若干行
这个 locals 让我迷惑不解,因为根据资料,express只是暴露了一个settings到app.locals,并没有暴露这个locals。
后来看了ejs的部分源码,才知道这个locals存在的原因,其实ejs工作机制的缘故。
现在开始说一下背景知识。
new Function的魔法
在js里,可以创建一个匿名函数,然后赋值给一个变量:var fn = function(x, y) { return x + y; };
但是,除了这种方法,还有一种更灵活的方法来创建前面的函数:
var fn = new Function("x, y", "return x + y;");
这是很多魔法的来源,它实际上代表了一种思想:用代码创造代码
with关键字
js里有一个with关键字, 先看个例子:var t = { name : { firstname: "tom" }, age: 12 } with (t.name) { console.log(firstname); // 输出 tom firstname = "jack" } console.log(t.name.firstname) // 输出 jack
没啥问题。但是,再看这个:
var t = { name : { firstname: "tom" }, age: 12 } with (t.name) { firstname = "jack" console.log(firstname); // 输出 jack console.log(t.name.firstname); //输出 jack t.name = { firstname: "mike" }; console.log(firstname); // 输出 jack console.log(t.name.firstname); //输出 mike } console.log(t.name.firstname) // 输出 mike
with里面发生了什么事情呢?其实很简单,可以这样理解上面的代码:
var t = { name : { firstname: "tom" }, age: 12 }; (function(scope) { scope.firstname = "jack" console.log(scope.firstname); // 输出 jack console.log(t.name.firstname); // 输出 jack , 因为现在scope 和 t.name 是 同一个对象 t.name = { firstname: "mike" }; console.log(scope.firstname); // 输出 jack,因为 scope 和 现在的t.name 是两个独立无关的对象了! console.log(t.name.firstname); //输出 mike })(t.name); // 把 t.name 传进去 console.log(t.name.firstname) // 输出 mike
所谓指向对象的变量,其实就是指针而已。
未完
相关文章推荐
- 关于模板引擎2--望批评指正
- 关于The function equals must be used with a prefix when a default namespace is not specified解决
- 关于模板引擎handlebars.js基本用法
- VTemplate模板引擎的使用—Function标签
- 关于模板引擎handlebars.js基本用法
- 关于The function size must be used with a prefix when a default namespace is not specified解决
- 关于Django模板引擎的研究
- 关于The function get must be used with a prefix when a default namespace is not specified的错误
- thinkphp—关于模板时间的获取(模板引擎是Smarty),该如何操作
- 关于js模板引擎 arttemplate 的使用
- 关于前段模板引擎
- 关于模板引擎的前言
- 关于Handlebars.java的模板引擎的使用
- 关于 underscore 中模板引擎的应用示例
- 关于 underscore 中模板引擎的应用演示样例
- 关于handlebars.js模板引擎
- 关于将Layui的模板引擎放入到弹框中,弹出!
- 关于thinkphp模板引擎中变量输入的思考
- VTemplate模板引擎的使用—Function标签
- 关于模板引擎--望批评指正