javascript定義函數的方法

來源:互聯網
上載者:User

以下是各種方法的範例程式碼 複製代碼 代碼如下:<html>
<head></head>
<body>
<script type="text/javascript">
/*javascript定義函數(聲明函數)可以有三種方法:正常方法、建構函式、函數直接量。*/
/*1.正常方法 function(param){}*/
function print(msg)
{
document.write(msg,"<br/>");
}
/*如果函數不包含return 語句,只執行函數體內語句,並返回undefined*/
/*2.建構函式方法:new Function()*/
var add1=new Function('a','b','return a+b');
/*3.函數直接量法,建立未命名函數,*/
var result = function(x,y){return x+y;};
/*也可以指定函數名*/
var result2 = function fact(x){if(x<1) return 1;else return x*fact(x-1)};
document.write('調用一般的方法:');
print("<hr/>");
print('調用建構函式方法:add1(5,6)');
print(add1(5,6));
print("<hr/>");
print("調用函數直接量法:result(3,4)");
var re =result(3,4);
print(re);
print("調用函數直接量法:result2(3)");
print(result2(3));
print("<hr/>");
print('函數作為資料使用');
/*函數可以作為資料使用*/
function add(x,y){return x+y;}
function subtract(x,y){return x-y;}
function multiply(x,y){return x*y;}
function divide(x,y){return x/y;}
function operate(operator,operand1,operand2)
{
return operator(operand1,operand2);
}
//計算(2+3) + (4*5)
var i = operate(add,operate(add,2,3),operate(multiply,4,5));
print('(2+3) + (4*5)='+i);
print("<hr/>");
//使用函數直接量
var operators = new Object();
operators['add'] = function(x,y){return x+y;}
operators['substract'] = function(x,y){return x-y;}
operators['multiply'] = function(x,y){return x*y;}
operators['divide'] = function(x,y){return x/y;}
operators['pow'] = Math.pow;
function operate2(op_name,operand1,operand2)
{
if(operators[op_name] == null) return "unknown operator";
else return operators[op_name](operand1,operand2);
}
//定義"hello" + "" + "world"
var j = operate2("add","hello",operate2("add"," ","world"));
var k = operate2("pow",10,2);
print(j);
print(k);
print("<hr/>");
</script>
</body>
</html>

運行結果為:
調用一般的方法:
--------------------------------------------------------------------------------
調用建構函式方法:add1(5,6)
11
--------------------------------------------------------------------------------
調用函數直接量法:result(3,4)
7
調用函數直接量法:result2(3)
6
--------------------------------------------------------------------------------
函數作為資料使用
(2+3) + (4*5)=25
--------------------------------------------------------------------------------
hello world
100

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.