I am implement following this.
//to_s.js
(function(){
String.prototype.to_s = function(){
var str = this.toString();
var convert = function(s){
return eval(s);
};
while(/#{(\w+)}/.test(str)){
// bad because I use eval...
var matchStr =RegExp.$1;
var str = str.replace(/#{(\w+)}/,convert(matchStr));
}
return str;
};
})();
module.exports = String.prototype.to_s;
// test/to_s_test.js
require("./../to_s");
var name = 33;
"hello #{name}".to_s();
I run to_s_test.js, but it happend error that 'name is undefined'.But I don't know why it happen.But change 'var name = 33' to name = 33 , It works... Do you have any idea? Thanks in advance.
It will only work without var
because eval
occurs in another context, and therefore only globals may be accessed using your method. A global is automatically created when you do not declare the variable; however, in node.js, variables declared in modules are not global.
This is why, as I previously mentioned, attempting to make languages conform to other languages' idioms is a bad idea.