日期:2014-05-16 浏览次数:20363 次
一、作为数据的函数
function square(x){return x*x} //定义了一个新的函数对象,并把这个对象赋给了变量 square var a=square(4); var b=square; var c=b(5); //除了赋给变量外,还可以赋给对象的属性,这种情况下,我们称函数为方法 var o=new object; o.square=function(x){return x*x} y=o.square(16); //函数也可以没有函数名 var a=new Array(3); a[0]=function(x){returnp x*x} a[1]=20; a[2]=a[0]{a[1]}; //将函数作为数据的所有用法 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); } var i=operate(add,operate(add,2,3),operate(multiply,4,5)); var operators={ add: function(x,y){return x+y}, subtract: function(x,y){return x-y}, multiply: function(x,y){return x*y}, divide: function(x,y){return x/y}, pow: Math.pow }; function operate2(op_name,operand1,operand2) { if(typeof operators[op_name]=="function") return operators[op_name](operand1,operand2); else throw "unknown operator"; } var j=operate2("add","hello",operates("add"," ","world")) var k=operate2("pow",10,2)二、作为方法的函数
//this 用来调用方法的对象成为关键字this的值 var calculator={ operand1:1, operand2:1, compute:function() { this.result=this.operand1+this.operand2; } }; calculator.compute(); print(calculator.result);