JS忍者祕籍-函數重載

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<script>
    function assert(value, desc) {
        var li = document.createElement("li");
        li.className = value ? "pass" : "fail";
        li.appendChild(document.createTextNode(desc));
        document.getElementById("results").appendChild(li);
    }
</script>
<style>
    #results li.pass {
        color: green;
    }

    #results li.fail {
        color: red;
    }
</style>
<body>
<ul id="results"></ul>
</body>
<script>
    console.log(window)
    debugger
    function addMethod(object, name, fn) {
        var old = object[name];
        debugger
        object[name] = function () {
            if (fn.length == arguments.length) {
                debugger
                return fn.apply(this, arguments)
            } else if(typeof old == 'function'){
                debugger
                return old.apply(this, arguments)
            }
        }
    }

    var ninjas = {
        values: ["Dean Edwards", "Sam Stephenson", "Alex Russell"]
    };
    
    addMethod(ninjas, "find", function () {
        return this.values;
    })
    

    addMethod(ninjas, "find", function (name) {
        var ret = [];
        for (var i = 0; i < this.values.length; i++) {
            if (this.values[i].indexOf(name) == 0) {
                ret.push(this.values[i]);
            }
        }
        return ret;
    })
    

    addMethod(ninjas, "find", function (first, last) {
        var ret = [];
        for (var i = 0; i < this.values.length; i++) {
            if (this.values[i] == (first + " " + last)) {
                ret.push(this.values[i])
            }
        }
        return ret;
    })

    assert(ninjas.find().length == 3, "Found all ninjas");
    assert(ninjas.find("Sam").length == 1, "Found ninja by first name");
    assert(ninjas.find("Dean", "Edwards").length == 1, "Found ninja by first and last name");
    assert(ninjas.find("Dean", "Edwards", "D") == null, "Found nothing");
</script>
</html>
相關文章
相關標籤/搜索