什么是编译的jst模板中的`this`

时间:2015-12-22 02:18:01

标签: javascript ejs

当ejs文件编译时,它变成了一个javascript函数。例如,这个ejs文件

<h3> Users Index</h3>
<ul>
  <% users.each(function (user) { %>
    <li><%= user.get("name") %></li>
  <% })%>
</ul>

编译到这个javascript函数:

(function() { this.JST || (this.JST = {}); this.JST["users/index"] =     function(obj){var __p=[],print=function(){__p.push.apply(__p,arguments);};with(obj||{}){__p.push('<h3> Users Index</h3>\n\n<ul>\n  ');  users.each(function (user) { ; __p.push('\n    <li>',  user.get("name") ,'</li>\n  ');  }); __p.push('\n</ul>\n\n');}return __p.join('');};
}).call(this);

在上面的javascript函数中,this引用了什么? (即骨干视图等)

1 个答案:

答案 0 :(得分:2)

如果你运行像这样的自执行函数结构

accelerometer
armv6
armv7
auto-focus-camera
bluetooth-le
camera-flash
front-facing-camera
gamekit
gps
gyroscope
healthkit
location-services
magnetometer
metal
microphone
opengles-1
opengles-2
opengles-3
peer-peer
sms
still-camera
telephony
video-camera
wifi

您会注意到它的输出(Chrome控制台输出)

(function() { console.log(this) }).call(this);

所以这一切只是将变量Window {external: Object, chrome: Object, document: document, i: undefined, StackExchange: Object…} 添加到全局(JST)命名空间中,以便在以后的每个脚本中都可以访问它。

window将确保this.JST || (this.JST = {});(我们看到的window.JST = window)存在,如果不存在则会创建它的值为空对象(this)。

相关问题