关于expres模板引擎,Function,with
生活随笔
收集整理的這篇文章主要介紹了
关于expres模板引擎,Function,with
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
2019獨角獸企業(yè)重金招聘Python工程師標(biāo)準(zhǔn)>>>
本文只是一些很零散的東西,關(guān)于js的模板引擎方面的知識。
看 Node in Action的時候,有一章關(guān)于ejs,看到這樣的一個片段:
<% if (locals.messages) { %> 后面省略若干行這個 locals 讓我迷惑不解,因為根據(jù)資料,express只是暴露了一個settings到app.locals,并沒有暴露這個locals。 后來看了ejs的部分源碼,才知道這個locals存在的原因,其實ejs工作機(jī)制的緣故。 現(xiàn)在開始說一下背景知識。
new Function的魔法
在js里,可以創(chuàng)建一個匿名函數(shù),然后賦值給一個變量:
var fn = function(x, y) { return x + y; };但是,除了這種方法,還有一種更靈活的方法來創(chuàng)建前面的函數(shù):
var fn = new Function("x, y", "return x + y;");這是很多魔法的來源,它實際上代表了一種思想:用代碼創(chuàng)造代碼
with關(guān)鍵字
js里有一個with關(guān)鍵字, 先看個例子:
var t = { name : { firstname: "tom" }, age: 12 } with (t.name) {console.log(firstname); // 輸出 tomfirstname = "jack" }console.log(t.name.firstname) // 輸出 jack沒啥問題。但是,再看這個:
var t = { name : { firstname: "tom" }, age: 12 } with (t.name) {firstname = "jack"console.log(firstname); // 輸出 jackconsole.log(t.name.firstname); //輸出 jackt.name = {firstname: "mike"};console.log(firstname); // 輸出 jackconsole.log(t.name.firstname); //輸出 mike }console.log(t.name.firstname) // 輸出 mikewith里面發(fā)生了什么事情呢?其實很簡單,可以這樣理解上面的代碼:
var t = { name : { firstname: "tom" }, age: 12 };(function(scope) { scope.firstname = "jack"console.log(scope.firstname); // 輸出 jackconsole.log(t.name.firstname); // 輸出 jack , 因為現(xiàn)在scope 和 t.name 是 同一個對象t.name = {firstname: "mike"};console.log(scope.firstname); // 輸出 jack,因為 scope 和 現(xiàn)在的t.name 是兩個獨立無關(guān)的對象了!console.log(t.name.firstname); //輸出 mike })(t.name); // 把 t.name 傳進(jìn)去console.log(t.name.firstname) // 輸出 mike所謂指向?qū)ο蟮淖兞?#xff0c;其實就是指針而已。
未完
轉(zhuǎn)載于:https://my.oschina.net/mustang/blog/265062
總結(jié)
以上是生活随笔為你收集整理的关于expres模板引擎,Function,with的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 力扣算法题—074搜索二维矩阵
- 下一篇: 解决Div自适应高度的方法(转)