javascript实现函数的默认參数值方法

近期在学python,得益于python中的decorator思路,想到在javascript中參数是不能定义默认值的,可是能够通过decorator给它模拟出来,话不多说,上代码

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title></title>
</head>
<body>

    <script type="text/javascript">
        function defaultArg(params, fun) {
            function f() {
                var args = [];
                for (i = 0; i < arguments.length || i < params.length; i++) {
                    if (i >= arguments.length || arguments[i] == null) {
                        args.push(params[i]);
                    }
                    else {
                        args.push(arguments[i]);
                    }
                }
                fun.apply(this, args);
            }
            return f;
        }
        function ClassA() {
            this.name = "ClassA";
        }
        ClassA.prototype.show = defaultArg(
            //尽管有点另类,但非常像decorator吧
            ["default1","default2"],
            function (arg1,arg2) {
                alert("[" + this.name + "]" + arg1 + "," + arg2);
        });

        var inst = new ClassA();
        inst.show();  //这里将使用默认參数
        inst.show("hello");
        inst.show("hello","world");
    </script>
</body>
</html>





原文地址:https://www.cnblogs.com/hrhguanli/p/4502982.html