6.31 js笔记

    技术2022-07-11  80

    函数重载

    如果JS函数需要实现重载的话,可以根据arguments对象的length值进行判断 如:

    function demo(a,b) { console.log(demo.length);//形参的个数 console.log(arguments.length);//实际参数个数 console.log(arguments[0]); console.log(arguments[1]); console.log(arguments[2]); } demo(4,5,6);

    <script type="text/javascript"> function add() { if (arguments.length == 1) { alert(arguments[0] + 10); } else if (arguments.length == 2) { alert(arguments[0] + arguments[1]); } } //函数调用 add(10); add(10, 20); </script>

    结果:依次弹出 20 30

    //可变长度实现 function add() { var total=0; for(var i=arguments.length-1;i>=0;i--){ total+=arguments[i]; }; return total; } console.log(add(1)); console.log(add(1,2));

    结果:

    function setting() { var ele=document.getElementById("js"); if(typeof arguments[0]==="object"){ for(p in arguments[0]){ ele.style[p]=arguments[0][p]; } }else{ ele.style.fontSize=arguments[0]; ele.style.backgroundColor=arguments[1]; } } // setting(18,"red"); setting({fontSize:20,backgroundColor:"green"});

    结果:

    function setting() { var ele=document.getElementById("js"); if(typeof arguments[0]==="object"){ for(p in arguments[0]){ ele.style[p]=arguments[0][p]; } }else{ ele.style.fontSize=arguments[0]; ele.style.backgroundColor=arguments[1]; } } setting(18,"red"); //setting({fontSize:20,backgroundColor:"green"});

    结果:

    模板:

    function fun1(obj) { alert(1) } function fun3(obj, obj1, obj2) { alert(3) } function fun2(obj, obj1) { alert(2) } function funAll(obj, obj1, obj2, obj3) { if ( arguments.length == 1) { fun1(obj); } else if ( arguments.length == 2) { fun2(obj, obj1); } else if ( arguments.length == 3) { fun3(obj, obj1, obj2); } //这里写代码 才能体现 重载的意义 // We Can do Something... } funAll(""); funAll("", ""); funAll("", "","");

    或者

    function overLoading() {   // 根据arguments.length,对不同的值进行不同的操作   switch(arguments.length) {     case 0:       /*操作1的代码写在这里*/       break;     case 1:       /*操作2的代码写在这里*/       break;     case 2:       /*操作3的代码写在这里*/          //后面还有很多的case...... } }

    方法重写

    function Parent() { this.run=function () { console.log("pasrsrr"); } } function Child() { Parent.call(this); var parentRun=this.run; this.run=function () { console.log("chilid is running"); parentRun(); }; } var c=new Child(); c.run();

    function Parent(){ } Parent.prototype.run =function () { console.log("parent"); }; Child.prototype = Object.create(Parent.prototype);//继承 Child.prototype.constructor=Child; Child.super=Parent.prototype; function Child(){ } Child.prototype.run=function () { console.log('chilid is running'); Child.super.run(); } var c= new Child(); c.run();

    Processed: 0.014, SQL: 9