Help with JS and functions parameters

后端 未结 6 1735
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-31 19:26

Does JS support two functions with the same name and different parameters ?

function f1(a, b)
{
// a and b are numbers
}

function f1(a, b, c)
{
// a is a string         


        
6条回答
  •  再見小時候
    2021-01-31 19:37

    You can also use instanceof, example with basic polymorphism.

    First create a superclass (ball)

    // superclass
    function Ball() {
        this.play = function() {
            alert("Ball throw");
        };
    }
    

    and now for some subclasses (types of balls)

    // subclass
    function Basketball() {
        this.play = function() {
            alert("basketball throw");
        };
    }
    // subclass
    function Soccerball() {
        this.play = function() {
            alert("soccer ball kick/throw");
            console.debug("here");
        };
    }
    // subclass
    function Baseball() {
        this.play = function() {
            alert("strike 3 you're out");
            console.debug("here");
        };
    }
    

    Give them Ball functionality, aka set their superclass via prototype

    // set subclass functionality
    Basketball.prototype = new Ball();
    Soccerball.prototype = new Ball();
    Baseball.prototype = new Ball();
    

    Some polymorphism (create a bunch of balls and play with them all, but play based on type)

    var bunchOfBalls = [new Baseball(), new Soccerball(), new Basketball()];
    for (var i = 0; i < bunchOfBalls.length; i++) {
        bunchOfBalls[i].play();
    }
    

    Now write a function that takes a ball but only want to to work for specific type of balls (mimic function overloading, more or less)

    //overloading dependent upon type
    function BasketbalOrBaseballOnlyPlay(aBall) {
        if (aBall instanceof Basketball) {
            //special basketball function
        }
        if (aBall instanceof Baseball) {
            //special baseball function
        }
    
    }
    

    If aBall is a Basketball so aBall = new Basketball(); then aBall instanceof Basketball would return true for Basketball and false for baseball but true for Ball.

    So aBall instanceof Ball would return true because a Basketball is a Ball.

    See code live at http://jsfiddle.net/kLCPB/

提交回复
热议问题