javascript将dotnotation字符串转换为对象

Har*_*rry 3 javascript node.js

我有一个"namespace.fun1.fun2.fun3"从客户端传递的字符串.它告诉服务器使用哪个功能.

我如何安全地运行该功能?

现在我正在做:

var runthis = string.split('.')
namespace[runthis[1]][runthis[2]][runthis[3]]
Run Code Online (Sandbox Code Playgroud)

如何安全地处理任意深度的嵌套?

jAn*_*ndy 5

我写的一个小功能.我在大多数应用程序中使用它:

Object.lookup = (function _lookup() {
    var cache = { };

    return function _lookupClosure( lookup, failGracefully ) {
        var check   = null,
            chain   = [ ],
            lastkey = '';

        if( typeof lookup === 'string' ) {
            if( cache[ lookup ] ) {
                chain = cache[ lookup ].chain;
                check = cache[ lookup ].check;
            }
            else {
                lookup.split( /\./ ).forEach(function _forEach( key, index, arr ) {
                    if( check ) {
                        if( typeof check === 'object' ) {
                            if( key in check ) {
                                chain.push( check = check[ key ] );
                                lastkey = key;
                            }
                            else {
                                if( !failGracefully ) {
                                    throw new TypeError( 'cannot resolve "' + key + '" in ' + lastkey );    
                                }
                            }
                        }
                        else {
                            if( !failGracefully ) {
                                throw new TypeError( '"' + check + '" ' + ' does not seem to be an object' );   
                            }
                        }
                    }
                    else {
                        lastkey = key;
                        chain.push( check = window[ key ] );
                    }
                });

                if( check ) {
                    cache[ lookup ] = {
                        chain: chain,
                        check: check
                    };
                }
            }
        }

        return {
            execute: function _execute() {
                return typeof check === 'function' ? check.apply( chain[chain.length - 2], arguments ) : null;
            },
            get: function _get() {
                return check;
            }
        };
    }
}());
Run Code Online (Sandbox Code Playgroud)

用法:

Object.lookup( 'namespace.fun1.fun2.fun3' ).execute();
Run Code Online (Sandbox Code Playgroud)

第一个参数是要解析的对象/方法/属性.第二个(可选)参数指示lookup()方法是否应以静默方式失败,或者如果某些属性或对象无法解析则抛出异常.默认是'throw'.避免那个电话

Object.lookup( 'namespace.fun1.fun2.fun3', true ).execute( 'with', 'paras' );
Run Code Online (Sandbox Code Playgroud)

如果.fun3是函数,则可以传入任何参数.execute().如果您只想收到属性值,也可以调用.get()而不是.execute()

var val = Object.lookup( 'namespace.fun1.fun2.fun3' ).get();
Run Code Online (Sandbox Code Playgroud)