JavaScript利用函数注释实现类似PHP heredoc的字符串存储

作者:木棉时间:2026-10-28 09:29:12浏览:463

本文介绍在JavaScript中通过Function.prototype扩展方法,利用函数内部的注释块来存储HTML字符串的技巧。该方法无需对字符串内容进行转义,可直接从函数源码中提取注释内容,实现类似PHP heredoc语法的效果,适用于模板字符串的便捷定义。

JavaScript利用函数注释实现类似PHP heredoc的字符串存储

作者具有PHP开发背景,联想到PHP中的<<<语法(包括heredoc和nowdoc模式),因此决定将此JavaScript技巧命名为heredoc。


具体实现代码如下:

 
Function.prototype.heredoc = function(){
// 利用 function 的注释来存储字符串,而且无需转义。
var _str = this.toString(),
s_pos = _str.indexOf("/*")+2,
e_pos = _str.lastIndexOf("*/");
return (s_pos<0 || e_pos<0) ? "" : _str.substring(s_pos, e_pos);
} 
function fn(){
/*<table>
<tr>
<td>用户名</td>
<td>密码</td>
</tr>
<tr>
<td style="widht:20px;">@name</td>
<td>zf123456</td>
</tr>
</table>*/
} 
var str_table = fn.heredoc();
console.log(str_table);
作者最新文章