本文主要是介绍6.31 js笔记,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
函数重载
如果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();
这篇关于6.31 js笔记的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!