避免使用javascript eval()函数

3

假设我想要像这样在字符串中添加变量插值:

String.prototype.interpolate = function() {
    return this.replace(/{(\S+?)}/g, function(match, $1) {return eval($1);});
}

如果我所有的变量都是全局或局部的,那么我可以用this[$1]替换eval($1)。但是如果我有像var name = {first: 'Joe', last: 'Blogs'};这样的东西,那么this[$1]将无法插入"Hello, {name.first} {name.last}!".interpolate()中。有没有什么东西可以代替eval()?如果我希望这些变量来自不受信任的来源,那么我真的不能使用eval()

1
你应该使用一些小型的模板引擎。阅读 http://ejohn.org/blog/javascript-micro-templating/,它非常小巧而且棘手 :) - biziclop
1个回答

1

如果您不想使用现有的模板引擎,我建议将要插值的数据明确化:

String.prototype.interpolate = function(data) {
    return this.replace(/{(\S+?)}/g, function(match, $1) {return data[$1];});
}

console.log( '{a} is better than {b}'.interpolate({'a':'explicit', 'b':'implicit'}) );

@biziclop:那个微型模板的东西非常好,但在使用'use strict';条件下不可用,因为它使用了with - Christopher Weiss
abesto:那肯定可以工作,但似乎违反了“不要重复自己”的原则。 - Christopher Weiss
@ChristopherWeiss:只有参数像这样直接构建时才是如此。在许多情况下,它将可用于预先存在的对象中。 - abesto

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接