我如何使用对象声明启动特定方法?

时间:2013-07-14 15:29:10

标签: javascript object

我有以下代码:

function foo(){
    this.bar = {
        images: function() {
            this.example = "string";
            this.anotherFoo = true;
            (...)
            this.getBigPicturePositions = function(){};
            return this;
        },
        search: function(){
            this.thing = "string";
            this.anotherBar = false;
            (...)
            this.newAjaxSearch = function(){};
            return this;
        }
    }
}

然后,我有这个声明:

var foo = new foo();
foo.start({
    bar: {
        images: {
            getBigPicturePositions: true
        },
        search: {
            newAjaxSearch: true,
            idontexist: true
        }
    }
});

如何创建这样的函数来启动指定的方法?我需要这个在我需要的时候启动特定的方法(如果它们当然存在的话)。在我的例子中,我需要得到类似的东西:

foo.bar.images().getBigPicturePositions();
foo.bar.search().newAjaxSearch();

感谢您的帮助!我是javascript对象的新手。


更新:问题已由CrazyTrain提供的解决方案解决,但我也更新了我的代码。要查看结果,请查看此Fiddle

1 个答案:

答案 0 :(得分:2)

首先,使.start()方法成为从new foo()

创建的对象的继承方法
foo.prototype.start = function(flags) {
    // call our recursive invoker function
    recursive_invoker(flags, this);
}

然后创建一个迭代对象的递归函数,并在找到时递归遍历嵌套对象,或者在给出true值时调用函数。

        // holds the flags---v     v---holds the methods
function recursive_invoker(flags, methods) {

    // enumerate the properties of the `flags` object
    for (var f in flags) {
        if (typeof flags[f] === "object" && typeof methods[f] === "object") {
            // objects were found, so make a recursive call with those objects
            recursive_invoker(flags[f], methods[f]);

        } else if (flags[f] === true && typeof methods[f] === "function") {
             // `true` was found, so invoke the function on the "methods" object
             methods[f]();

        } else {
            // Either we found `false`, or an object was not found, so do nothing.
            // This `else` isn't really needed.
        }
    }
}