Home > Web Front-end > JS Tutorial > body text

Detailed explanation of function overloading in JavaScript

php中世界最好的语言
Release: 2018-03-09 13:28:35
Original
1571 people have browsed it

This time I will bring you a detailed explanation of JavaScript function overloading. What are the precautions for JavaScript function overloading? The following is a practical case, let’s take a look.

function addMethod(object, name, fn){    var old = object[name];
    object[name] = function()    {        if (fn.length == arguments.length)            return fn.apply(this, arguments);        else if (typeof old == 'function')            return old.apply(this, arguments);
    };
}// 不传参数时,返回所有namefunction find0(){      return this.names;
}// 传一个参数时,返回firstName匹配的namefunction find1(firstName){      var result = [];      for (var i = 0; i < this.names.length; i++)
    {            if (this.names[i].indexOf(firstName) === 0)
        {      
            result.push(this.names[i]);    
        }  
    }      return result;
}// 传两个参数时,返回firstName和lastName都匹配的namefunction find2(firstName, lastName){     var result = [];      for (var i = 0; i < this.names.length; i++)
    {            if (this.names[i] === (firstName + " " + lastName))
        {      
            result.push(this.names[i]);    
        }  
    }      return result;
}function Users(){
    addMethod(Users.prototype, "find", find0);
    addMethod(Users.prototype, "find", find1);
    addMethod(Users.prototype, "find", find2);
}var users = new Users();
users.names = ["John Resig", "John Russell", "Dean Tom"];console.log(users.find()); // 输出[ 'John Resig', 'John Russell', 'Dean Tom' ]console.log(users.find("John")); // 输出[ 'John Resig', 'John Russell' ]console.log(users.find("John", "Resig")); // 输出[ 'John Resig' ]console.log(users.find("John", "E", "Resig")); // 输出undefined
Copy after login

I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website!

Related reading:

How to use negative margin values ​​in CSS

A useful jquery Form validation plug-in

Four ways to declare functions in js

The above is the detailed content of Detailed explanation of function overloading in JavaScript. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!