1

我有以下代码:

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

4

1 回答 1

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.
        }
    }
}
于 2013-07-14T16:09:57.783 回答