1.作为函数调用
function my(a,b){
return a*b;
}
var a=10,b=3,sum;
sum=my(a,b);
document.write(sum);
2.作为对象的方法调用
使用方式“对象.方法”
(1) 对象中定义的方法:
var people={
name:"name",
age:24,
printpeople:function(){
return this.name + this.age;
}
}
document.write(people.printpeople());
(2)从prototype继承的方法
Array.prototype.myFunction=function(){
for(i=0;i<this.length;i++){
this[i]=this[i][0].toUpperCase()+
this[i].substring(1,this[i].length);
}
}
var arr = ["benchi","dazhong"];
arr.myFunction();
document.write(arr);
3.使用构造函数调用函数
new即是使用构造函数的关键字。
function people(name,age){
this.name = name;
this.age = age;
this.print=print;
function print(){
document.write(this.name + this.age);
}
}
var person = new people("liming",24);
person.print();
4.一个函数作为另一个函数(对象)的方法被函数(对象)调用
在JavaScript中,函数也是对象,函数有其属性和方法,call() 和 apply() 是预定义的函数方法。
function myFunction(a, b) {
return a * b;
}
myObject = myFunction.call(myObject, 10, 2);