node.js require issue


I am implement following this.

String.prototype.to_s = function(){
        var str = this.toString();
        var convert = function(s){
            return eval(s);


            // 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


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.

Problem courtesy of: nobinobiru


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.

Solution courtesy of: user1479055


There is currently no discussion for this recipe.

This recipe can be found in it's original form on Stack Over Flow.