function的toString方法

javascript的创建多行字符串的除了平时常见的”“+ 反斜杠\ 还有ES6的` `

js51上发现一个很有意思的方法

function heredoc(fn) {
    return fn.toString().split('\n').slice(1,-1).join('\n') + '\n'
}
var tmpl = heredoc(function(){/*
    !!! 5
    html
      include header
      body
        //if IE 6
            .alert.alert-error
                center 对不起,我们不支持IE6,请升级你的浏览器
                    a(href="http://windows.microsoft.com/zh-CN/internet-explorer/download-ie") | IE8官方下载
                    a(href="https://www.google.com/intl/en/chrome/browser/") | Chrome下载
        include head
        .container
            .row-fluid
                .span8
                    block main
                    include pagerbar
                .span4
                    include sidebar
        include footer
        include script
 */});

优点:

模板字符串内不必写多余的任何字符,干净,简单
真正意义上的多行字符串, 有\n哦

缺点 :

不可以在单个字符串中添加js逻辑
容易被压缩器压缩掉,yui compressor可以通过/*!来避免被压缩掉,uglifyjs和gcc也可以通过选项配置不删除特定的注释,这个不是大问题

posted @ 2019-04-02 22:08  笠航  阅读(1886)  评论(0编辑  收藏  举报