可选参数 JavaScript 技巧

Optional arguments javascript trick

本文关键字:技巧 JavaScript 参数      更新时间:2023-09-26

我正在尝试执行以下操作:

eventService.emit = function(name, optionalArg1, optionalArg2,... ){
    $rootScope.$broadcast(name, optionalArg1, optionalArg2,...);
};

具有无限数量的可选参数。(广播"定义":$broadcast(字符串,参数...

我以为

eventService.emit =$rootScope.$broadcast;

可以工作,但它不能($broadcast函数可以访问$rootscope属性)和

eventService.emit = function(){
    $rootScope.$broadcast(arguments);
};

似乎不起作用

感谢您的帮助

原始代码:

services.factory('eventService', function($rootScope, $http){
    var eventObject = {};
    eventObject.emit = function(name){
       $rootScope.$broadcast(name);
    };
    return eventObject;
});
你可以

试试

eventService.emit = function(){
    $rootScope.$broadcast.apply($rootScope, arguments); //you can change "this" to whatever you need
};

在这里,您使用参数"array"中的参数执行$rootScope.$broadcast(它实际上不是一个数组,但行为类似于一个数组),并在函数中使用这个(参数)。

您可以使用

apply()(此处的文档):

eventService.emit = function(name, optionalArg1, optionalArg2,... )
{
    $rootScope.$broadcast.apply(this, arguments);
};

[1]:

当我想要很多选择时,我所做的是这样的:

function myFunction(options){
 if( options["whateverOptionYouWant"] != undefined ){
  //TODO: implement whatever option you want
 }
 if( options["whateverOTHEROptionYouWant"] != undefined ){
  //TODO: implement whatever OTHER option you want
 }
}

等等,我需要尽可能多的选项。

这样称呼它:

myFunction({ whateverOptionYouWant: "some option variable" });
myFunction();
myFunction({ 
 whateverOptionYouWant: "some option variable", 
 whateverOTHEROptionYouWant: "some other variable"});