`

JavaScript方法重载两招

阅读更多

function a(a ,b){

	if(b == void 0){
	  alert(2)
	}else{

	  alert(1)
	}

}












<script type='text/javascript'>

function ABC()
{
    this.member = 1;
    this.method = Show;
}
function Show(a,b,c)
{
    this.member = 123;
    if(arguments.length==1)
        if(arguments[0].constructor == Number)
            Show1_int.apply(this, arguments);
        else if(arguments[0].constructor == Date)
            Show1_date.apply(this, arguments);
        else
            Show1_string.apply(this, arguments);
    if(arguments.length==2)
        if(arguments[0].constructor == Array)
            Show3.apply(this,arguments);
        else
            Show2.apply(this,arguments);
}
function Show1_int(a)
{
    alert('1 integer input parameter ' + a+ '  methode is called');
}
function Show1_string(a)
{
    alert('1 string input parameter ' + a+ '  methode is called');
}
function Show1_date(a)
{
    alert('1 date input parameter ' + a+ '  methode is called');
}

function Show2(a,b)
{
    alert('2 input parameter is transfer:\na:'+a+'\nb:'+b + '\nthe member is' + this.member);
}
// 演示引用方式传递
function Show3(a,b)
{
    arguments[0][0]=2;
    alert('2 input parameter is transfer:\na:'+a+'\nb:'+b + '\nthe member is' + this.member);
}
var o = new ABC();
var arr = new Array();
arr[0]=321;
o.method(arr[0],2);    // 值传递
alert(arr[0]);        // 原始值未改变
o.method(arr,2);    // 引用方式传递
alert(arr[0]);        // 方法调用时被方法修改
o.method(new Date());

</script>
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics