js 覆蓋和重載 函數
2024-05-06 14:13:45
供稿:網友
學過JAVA的人對函數的覆蓋和重載肯定是再熟悉不過了。
重載指兩個或多個函數的參數類型,順序和數量以及返回值不一樣。
覆蓋指兩個或多個函數的參數類型,順序和數量以及返回值完全一樣。
那javascript真的有這種特性么?
回答是JS中函數重名只會采用最后一個定義。
首先來看下下面的代碼
代碼如下:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<TITLE> New Document </TITLE>
<META NAME="Generator" CONTENT="EditPlus">
<META NAME="Author" CONTENT="">
<META NAME="Keywords" CONTENT="">
<META NAME="Description" CONTENT="">
</HEAD>
<SCRIPT LANGUAGE="JavaScript">
<!--
//展現結果
function showResult(result) {
var showDiv = document.getElementById('result');
showDiv.innerHTML = '';
showDiv.innerHTML = result;
};
//展現結果2
function showResult2(result) {
var showDiv = document.getElementById('result2');
showDiv.innerHTML = '';
showDiv.innerHTML = result;
};
//展現結果3
function showResult3(result) {
var showDiv = document.getElementById('result3');
showDiv.innerHTML = '';
showDiv.innerHTML = result;
};
//測試同名方法
function testFun() {
showResult('this is a function named /'testFun/' with no arguments.');
};
function testFun(arg) {
showResult('this is a function named /'testFun/' with one argument,the argument is '+arg);
};
//2th測試,交換兩個函數的順序
//測試同名方法
function testFun2(arg) {
showResult2('this is a function named /'testFun2/' with one argument,the argument is '+arg);
};
function testFun2() {
showResult2('this is a function named /'testFun2/' with no arguments.');
};