开发者

Calling Method represented by string

开发者 https://www.devze.com 2023-03-25 16:48 出处:网络
I am being passed a string similar to below. \"User开发者_StackOverflow中文版s_Controller.login\"

I am being passed a string similar to below.

"User开发者_StackOverflow中文版s_Controller.login"

"Users_Controller" represents the object below. And "login" a method within it.

var Users_Controller = ( function () {
return{

  login : function(vo, callback)
   {......}

 }
 })();

Given only the string as a pointer,is it possible call the method?


You can use this function:

function getPropertyFromString(str, start) {
    str = str.split(".");
    var prop = start || window;
    for (var i = 0; i < str.length; i++) {
        if(prop == undefined)
          return prop;
        else
          prop = prop[str[i]];
    }
    return prop;
}
getPropertyFromString("Users_Controller.login");

However, this does not allow bracket syntax.


Something like this?

var Users_Controller = (function () {
    return {

        login: function (name) {
            alert("hello " + name);
        },
        logout: function (name) { alert("goodbye "+name); }

    }
})();


var methods = {};

for (method in Users_Controller) {
    methods["Users_Controller." + method] = Users_Controller[method];
}

methods["Users_Controller.login"]('john');
methods["Users_Controller.logout"]('john');
0

精彩评论

暂无评论...
验证码 换一张
取 消