Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/85.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript中的方法重载_Javascript_Jquery_Overloading - Fatal编程技术网

Javascript中的方法重载

Javascript中的方法重载,javascript,jquery,overloading,Javascript,Jquery,Overloading,我在Javascript代码中使用方法重载,如下所示 function somefunction() { //1st function } function somefunction(a) { //2nd function } function somefunction(a,b) { //3rd function } somefunction(); // function call goes here 我不明白的是,如果我调用somefunction()javascr

我在Javascript代码中使用方法重载,如下所示

function somefunction()
{
    //1st function
}

function somefunction(a)
{
   //2nd function
}

function somefunction(a,b)
{
   //3rd function
}

somefunction(); // function call goes here

我不明白的是,如果我调用
somefunction()
javascript应该调用第一个函数,但问题是javascript实际上调用了第三个函数。为什么呢?如何调用第一个和第二个函数?这是什么原因?有没有合适的方法在Javascript中实现方法重载?行业标准是什么?

您只是用每个新声明删除变量
somefunction

这相当于

   window.somefunction = function(...
   window.somefunction = function(...
   window.somefunction = function(...
Javascript不提供方法重载

正确的方法是:

  • 定义第三个函数并测试定义了哪些参数
  • 只传递一个包含参数的对象(这并不是真正的不同,但更干净)

JavaScript不支持方法重载(如在Java或类似语言中),您的第三个函数将覆盖前面的声明

相反,它通过支持变量参数。你可以

function somefunction(a, b) {
    if (arguments.length == 0) { // a, b are undefined
        // 1st body
    } else if (arguments.length == 1) { // b is undefined
        // 2nd body
    } else if (arguments.length == 2) { // both have values
        // 3rd body
    } // else throw new SyntaxError?
}

您还可以检查a==“undefined”等的
typeof,这将允许调用
somefunction(undefined)
,其中
参数。length
1
。这可能允许更轻松地调用各种参数,例如,当您可能有空变量时。

JS将
未定义的
传递给任何未提供的参数。如果需要重载之类的操作,则需要执行类似于以下代码的操作:

function someFunction(a, b) {
    if (typeof a === 'undefined') {
        // Do the 0-parameter logic
    } else if (typeof b === 'undefined') {
        // Do the 1-parameter logic
    } else {
        // Do the 2-parameter logic
    }
}

不能在JavaScript中重载方法。在javascript中,函数存储在变量中。全局变量存储在窗口对象上。每个具有相同名称的对象只能有一个属性(独占密钥哈希)

您可以做的是使用最多的参数定义定义,并检查传入的参数数量

function Test(a, b, c)
{
    if(typeof a == 'undefined') 
    {
        a = 1;
    }

    if(typeof b == 'undefined') 
    {
        b = "hi";
    }

    if(typeof c == 'undefined') 
    {
        c = Date.Now;
    }
}

现在如果我调用Test(),它的作用就好像我调用了
Test(1,“hi”,Date.Now)
JavaScript中没有真正的函数重载,因为它允许传递任意类型的任意数量的参数。最好的做法是创建一个函数 比如: myfunc(可选)


我试图为这个问题找到一个优雅的解决方案。你可以找到演示。用法如下所示:

var out = def({
    'int': function(a) {
        alert('Here is int '+a);
    },

    'float': function(a) {
        alert('Here is float '+a);
    },

    'string': function(a) {
        alert('Here is string '+a);
    },

    'int,string': function(a, b) {
        alert('Here is an int '+a+' and a string '+b);
    },
    'default': function(obj) {
        alert('Here is some other value '+ obj);
    }

});

out('ten');
out(1);
out(2, 'robot');
out(2.5);
out(true);
实现这一目标的方法如下:

var def = function(functions, parent) {
 return function() {
    var types = [];
    var args = [];
    eachArg(arguments, function(i, elem) {
        args.push(elem);
        types.push(whatis(elem));
    });
    if(functions.hasOwnProperty(types.join())) {
        return functions[types.join()].apply(parent, args);
    } else {
        if (typeof functions === 'function')
            return functions.apply(parent, args);
        if (functions.hasOwnProperty('default'))
            return functions['default'].apply(parent, args);        
    }
  };
};

var eachArg = function(args, fn) {
 var i = 0;
 while (args.hasOwnProperty(i)) {
    if(fn !== undefined)
        fn(i, args[i]);
    i++;
 }
 return i-1;
};

var whatis = function(val) {

 if(val === undefined)
    return 'undefined';
 if(val === null)
    return 'null';

 var type = typeof val;

 if(type === 'object') {
    if(val.hasOwnProperty('length') && val.hasOwnProperty('push'))
        return 'array';
    if(val.hasOwnProperty('getDate') && val.hasOwnProperty('toLocaleTimeString'))
        return 'date';
    if(val.hasOwnProperty('toExponential'))
        type = 'number';
    if(val.hasOwnProperty('substring') && val.hasOwnProperty('length'))
        return 'string';
 }

 if(type === 'number') {
    if(val.toString().indexOf('.') > 0)
        return 'float';
    else
        return 'int';
 }

 return type;
};
我不明白的是,如果我调用somefunction()javascript应该调用第一个函数,但问题是javascript实际上调用了第三个函数

这是预期的行为

为什么呢

问题在于JavaScript本身不支持方法重载。因此,如果它看到或解析两个或多个具有相同名称的函数,它将只考虑最后定义的函数并覆盖以前的函数。 为什么呢?如何调用第一个和第二个函数?这是什么原因

我认为适合大多数情况的方法之一是:

假设你有一个方法

function foo(x)
{
} 
您可以定义一个新方法,而不是重载方法,这在javascript中是不可能的

fooNew(x,y,z)
{
}
然后修改第一个函数,如下所示-

function foo(x)
{
  if(arguments.length==2)
  {
     return fooNew(arguments[0],  arguments[1]);
  }
} 

如果有很多这样的重载方法,请考虑使用<代码>开关 > > < <代码> >如果是其他< /COD>语句。< /P> 有没有合适的方法来实现方法重载?行业标准是什么


目前还没有这样的标准,也没有一种更成熟的方法可以在javascript中进行方法重载。人们应该做最适合他们的编程设计的事情我想说,简单地打开参数长度,检查类型是否未定义就足够了。

JavaScript不直接支持方法重载。 下面是一个示例,说明如何实现类似的目标,如下所示:

function overloadMethod(object, name, fn){

            if(!object._overload){
            object._overload = {};
            }

            if(!object._overload[name]){
            object._overload[name] = {};
            }

            if(!object._overload[name][fn.length]){
            object._overload[name][fn.length] = fn;
            }

              object[name] = function() {
                        if(this._overload[name][arguments.length])
                        return this._overload[name][arguments.length].apply(this, arguments);
              };
}

function Students(){
  overloadMethod(this, "find", function(){
            // Find a student by name
  });

  overloadMethod(this, "find", function(first, last){
            // Find a student by first and last name
  });

}

var students = new Students();
students.find(); // Finds all
students.find("Rahul"); // Finds students by name
students.find("Rahul", "Mhatre"); // Finds users by first and last name

来源:

参数对象用于创建类似于概念的方法重载


参数是一种特殊类型的对象,仅在函数执行上下文中可用

参数。length属性用于标识传递到函数中的参数数量


您可以更好地使用第一类函数来创建假方法重载。完整的概念在我自己的网站上解释:

如果使用类,则创建两个不同的类,它们具有相同的方法和不同的参数。然后,您可以使用扩展运算符和依赖项注入来模拟重载行为

class-Foo{
方法(){
log('hello from method foo')
}
}
分类栏{
方法(名称){
log(`hello from method bar.Name是${Name}`)
}
}
功能负载(obj,选项){
对象方法(…选项)
}
const obj1=new Foo()
常量obj2=新条()
最小覆盖负载(obj1,[])

MimicOverload(obj2,['overloaded'])
在JavaScript中不能这样做。定义一个函数,然后在其内部有分支来覆盖各种参数组合。那么如何在javascript中使用面向对象的实践呢?javascript确实处理未经批准的变量。因此,只需创建一个接受(a,b)并读取输入的函数,即可确定执行路径。@Dasun哪个对象装饰实践?@Šime Vidas方法重载此答案为false。函数somefunc(){};将与var somefunc=function(){}进行比较;作为证明,如果以后声明另一个函数function(){window.somefunc();您好,请记住在共享网站链接时披露您与网站的连接!Tyler我在我的博客文章中解释了方法重载的概念。这就是为什么添加了我的博客链接是的,但您需要在回答中指出网站是您的。如果只传递了一个参数,我如何知道它是哪个参数到函数调用..?比如
somefunction(something);
@RohitSharma如果只有一个,那么它是第一个。JavaScript不支持命名参数
function overloadMethod(object, name, fn){

            if(!object._overload){
            object._overload = {};
            }

            if(!object._overload[name]){
            object._overload[name] = {};
            }

            if(!object._overload[name][fn.length]){
            object._overload[name][fn.length] = fn;
            }

              object[name] = function() {
                        if(this._overload[name][arguments.length])
                        return this._overload[name][arguments.length].apply(this, arguments);
              };
}

function Students(){
  overloadMethod(this, "find", function(){
            // Find a student by name
  });

  overloadMethod(this, "find", function(first, last){
            // Find a student by first and last name
  });

}

var students = new Students();
students.find(); // Finds all
students.find("Rahul"); // Finds students by name
students.find("Rahul", "Mhatre"); // Finds users by first and last name