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

作者:木棉

时间:2026-10-28

浏览:462

本文介绍在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);

实用工具推荐

电子包浆

绿化、压缩、噪点和虚拟水印,自由调节做旧程度。

使用 ›
图片压缩

选择画质和输出格式,预览压缩前后的大小。

使用 ›
相关文章