Javascript对象传递参数

时间:2013-08-08 09:39:49

标签: javascript jquery oop

我写了一个对象并且工作正常,但我对它不满意,因为我认为它可以改进:

这是:

var Modal = {

    init: function (contact1,contact2,aboutus1,aboutus2,terms1,terms2,privacy1,privacy2) {

        $(".modaltrigger").removeAttr("target");

        $(".modaltrigger").click(function () {

            if ($(this).is("#contact")) {

                $('#primary_url').attr('href', contact1);
                $('#secondary_url').attr('href', contact2);

            } else if ($(this).is("#aboutus")) {

                $('#primary_url').attr('href', aboutus1);
                $('#secondary_url').attr('href', aboutus2);

            } else if ($(this).is("#termsconditions")) {

                $('#primary_url').attr('href', terms1);
                $('#secondary_url').attr('href', terms2);

            } else if ($(this).is("#privacy")) {

                $('#primary_url').attr('href', privacy1);
                $('#secondary_url').attr('href', privacy2);
            }
        });
    }
};

我将上述方法称为:

Modal.init("test.com","test2.com","test3.com", "test4.com","test5.com", "test6.com","test7.com","test8.com");

以上工作正常,但如果我有长字符串值要通过怎么办?有没有办法,我可以将变量声明为参数,并且在调用方法时,我动态分配变量?我该如何编写代码..

我正在考虑将该方法称为:

Modal.init({
 var 1: "firstsrting",
 var 2: "secondsting",
 ...
 ...
});

请帮助..

1 个答案:

答案 0 :(得分:0)

只需将object用作一个参数。

var Modal = {

    init: function (params) {

        $(".modaltrigger").removeAttr("target");

        $(".modaltrigger").click(function () {

            if ($(this).is("#contact")) {

                $('#primary_url').attr('href', params.contact1);
                $('#secondary_url').attr('href', params.contact2);

            } else if ($(this).is("#aboutus")) {

                $('#primary_url').attr('href', params.aboutus1);
                $('#secondary_url').attr('href', params.aboutus2);

            } else if ($(this).is("#termsconditions")) {

                $('#primary_url').attr('href', params.terms1);
                $('#secondary_url').attr('href', params.terms2);

            } else if ($(this).is("#privacy")) {

                $('#primary_url').attr('href', params.privacy1);
                $('#secondary_url').attr('href', params.privacy2);
            }
        });
    }
};

并使用以下方法调用该函数(方法):

Modal.init({
    contact1: "http://test1.com",
    contact2: "http://test2.com",
    ...
    ...
});