一种在网页中调用可变长度JavaScript方法的智能方法

问题描述 投票:-1回答:3

我创建了一个新的Web应用程序,有10个页面/表单,在加载这些页面时,6个页面/表单调用相同的JavaScript方法,4个调用相同的加上一些其他方法。我显然可以在页面中单独调用这些方法,但我想知道如何以更智能的方式执行此操作。

目前我正在做的就是调用页面底部的方法,如:

<script>
 somemethod1(someparam1);
somemethod2(someparam1, someparam2);
somemethod3();
somemethod4();
somemethod5(someparam1);
</script>

打电话会更好:

<script>
 Execute('somemethod1', 'somemethod2''somemethod3', 'somemethod4', 'somemethod5')();
</script>
javascript
3个回答
0
投票

我不认为这是一个很好的做法。但是可以肯定的是,如果您不需要传递任何参数,那么使用Execute函数会更好。

你可以这样做,

function test1() {
  console.log('test1');
}

function test2() {
  console.log('test2');
}

var Execute = function() {
  for (var i = 0; i < arguments.length; i++) {
    var funcName = arguments[i];

    if (typeof window[funcName] == 'function') {
      window[funcName]();
    }
  }
}

Execute('test1', 'test2')

但是,正如您的问题编辑所示,您需要将特定参数传递给一个或多个函数,这是实现它的智能方法。

test1(param1);
test2(param2, param1);

0
投票

如果你有统一的程序,你需要按照一定的顺序调用它们,比如下面的迭代嵌套数组的例子,那么你可以使用给定的提议,它之前使用了以下函数。

这可能不适用于其他需求。

function Callback(array) {
    this.array = array;
}

Object.defineProperties(Callback.prototype, {
    start: {
        get: function () {
            return this.getCallback(0);
        }
    },
    getCallback: {
        value: function (i) {
            var that = this;
            return this.array[i].bind({ get next() { return that.getCallback(i + 1); } });
        }
    }
});

// example
function getSubmodel(model, submodel) {
    var callback = new Callback([
            function (a) { a.Categories.forEach(this.next); },
            function (a) { a.forEach(this.next); },
            function (a) { if (a.brandname === model) { a.models.forEach(this.next); } },
            function (a) { if (a.name === submodel) { a.submodel.forEach(this.next); } },
            function (a) { result.push(a.name); }
        ]),
        result = [];

    data.forEach(callback.start);
    return result;
}

var data = [{
        Storename: "Zig Zag Mobiles",
        Shopid: "asdef1234",
        Categories: [[{
            models: [{
                submodel: [{
                    price: null,
                    name: "Lumia 735 TS"
                }, {
                    price: "3200",
                    name: "Lumia 510"
                }], name: "Lumia"
            }],
            brandname: "Nokia",
        }]]
    }];

console.log(getSubmodel('Nokia', 'Lumia'));
.as-console-wrapper { max-height: 100% !important; top: 0; }

-1
投票

打电话给Execute('somemethod1', 'somemethod2''somemethod3', 'somemethod4', 'somemethod5')();会更好

如果您不需要将参数传递给单个方法,则可以执行以下操作:

[func1, func2, func3].map(function(func){
    func();
});

否则,执行此操作的方法是仅使用所需的参数调用方法,除非通过创建抽象获得真正重要的好处,您可以传入要调用的方法及其关联的参数。

© www.soinside.com 2019 - 2024. All rights reserved.