日期:2014-05-16 浏览次数:20579 次
???? 这几天有太忙了,还是简单的用代码说点问题吧。
?
function multi(x,y){
//函数名.length 得到形参的个数 arguments得到实参的个数,arguments是函JS函数内置的对象
try{
if(multi.length!=arguments.length) throw new Error("参数个数不符");
}catch(e){
alert(e.message);
return null;
}
this.x=x;
this.y=y;
this.value=this.x*this.y;
}
var a=new multi(3,4);
//this代表当前函数对象的引用
function test(x,y){
this.constructor(this.x+x,this.y+y);//constructor可以得到当前函数的构造函数
}
function add(x,y){
this.x=x;
this.y=y;
this.value=this.x+this.y;
}
a.t=test;//a变为了函数test的所有者,test里面的this会变成对multi函数的引用
test.call(a,1,2);//call方法提供了对当前函数对象所有者的调用,相当于a.test(1,2),还有一个类似的是apply
alert(a.value);
var b=new add(3,4);
b.b=test;//b变为了函数test的所有者,test里面的this会变成对add函数的引用
test.call(b,1,2);
alert(b.value);
//函数的调用者示例
function called() {
if (called.caller) {
alert(called.caller.arguments[0]);
} else {
alert("top function");//没有调用的会返回null,叫顶层
}
}
function demoCall() {
called();
}
demoCall();
demoCall(55);
//参数还有一个方法叫callee具体就不在写了。
?