Js函数将多个参数作为单个对象传递
Js function pass multiple parameters as a single object
我有以下构造函数:
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
相关文章:
- 如何使用javascript从JSON访问单个对象
- 将一个对象集合映射到汇总集合的单个对象
- 高级布线和单个对象定义
- 如何在返回单个对象时递归使用 Array.prototype.find()
- 使用Handlebars获取同级JSON数据,其中单个对象没有父索引键,但多个项有一个索引键
- 如何在javascript中的单个对象中推送类似的索引类型键
- NodeJS + mysql:选择返回单个对象的查询
- 在javascript(Angularjs)中将对象数组转换为单个对象
- 更改 JS 数组中的单个对象会更改所有元素
- 将数据格式从单个对象转换为键值对的对象数组
- 此函数如何能够返回单个对象
- ng-重复对象数组和单个对象
- 当您有集合时,调用接收单个对象作为参数的函数的最佳方法是什么
- 将单个对象提取为对象,而不是具有一个对象的数组,Javascript
- 在将 svg 加载到画布后获取单个对象
- 我需要使用单独类中的方法将单个对象与数组进行比较
- 检查 s3 存储桶中是否存在单个对象
- 将数组的多个项目映射到单个对象/函数
- 从 Node.js 中数组中单个对象的单个属性中获取值
- 从 NG 绑定结果访问单个对象