Js函数将多个参数作为单个对象传递

Js function pass multiple parameters as a single object

本文关键字:单个 对象 参数 函数 Js      更新时间:2023-09-26

我有以下构造函数:

var one = new HB.hideShowFacilites.Selectors(".facilities .more-centered", "more-centered", "less-centered", "container-max-height", ".facilities .container-min-height");  

是否有一种方法传递所有这些选择器作为一个单一的对象?

HB.hideShowFacilites = HB.hideShowFacilites || {};
HB.hideShowFacilites.Selectors = function(sel1, sel2, sel3, sel4, sel5){
    this.sel1 = sel1;
    this.sel2 = sel2;
    this.sel3 = sel3;
    this.sel4 = sel4;
    this.sel5 = sel5;
};
HB.hideShowFacilites.Selectors.prototype.hideShow = function(){
    var $obj1 = $(this.sel1),
        $obj2 = this.sel2,
        $obj3 = this.sel3;
        $obj4 = this.sel4,
        $obj5 = $(this.sel5);
    $obj1.on('click', function(e){
        e.preventDefault();
        if($obj1.hasClass($obj2)){
            $obj1.removeClass($obj2).addClass($obj3);
            $obj5.addClass($obj4);
        }
        else{
            $obj1.removeClass($obj3).addClass($obj2);
            $obj5.removeClass($obj4);
        }      
    });
};
$(document).ready(function(){
    var one = new HB.hideShowFacilites.Selectors(".facilities .more-centered", "more-centered", "less-centered", "container-max-height", ".facilities .container-min-height");
    one.hideShow();
});

根据HB.hideShowFacilites.Selectors的实现方式,您可以像这样使用Function.prototype.apply

function foo(args) {
    var instance = Object.create(HB.hideShowFacilites.Selectors.prototype);
    HB.hideShowFacilites.Selectors.apply(instance, args);
    return instance;
}
var one = foo([".facilities .more-centered", "more-centered", "less-centered", "container-max-height", ".facilities .container-min-height"]);  

在纯JS中,不可能在函数中传入带参数列表的对象,其成员将被视为参数,而不像这样修改函数:

HB.hideShowFacilites.Selectors = function(selectors){
    this.sel1 = selectors.sel1;
    this.sel2 = selectors.sel2;
    this.sel3 = selectors.sel3;
    this.sel4 = selectors.sel4;
    this.sel5 = selectors.sel5;
};
像这样的

函数需要一个参数,并将其视为具有sel1, sel2等字段的对象。

但反过来,也可以在函数中使用传入的参数列表作为数组:

HB.hideShowFacilites.Selectors = function(sel1, sel2, sel3, sel4, sel5){
    this.sel1 = arguments[0];
    this.sel2 = arguments[1];
    this.sel3 = arguments[2];
    this.sel4 = arguments[3];
    this.sel5 = arguments[4];
};

此外,如果您不喜欢修改该函数,则可以使用以下内容重新定义它

HB.myHideShowFacilites = function(){};
HB.myHideShowFacilites.prototype = HB.hideShowFacilites;
HB.hideShowFacilites.Selectors = function(selectors){
    this.sel1 = selectors.sel1;
    this.sel2 = selectors.sel2;
    this.sel3 = selectors.sel3;
    this.sel4 = selectors.sel4;
    this.sel5 = selectors.sel5;
};

,然后使用HB。myHideShowFacilites代替HB.hideShowFacilites