<html>
<head>
<title>用call和apply调用函数</title>
</head>
<body>
<script>
<!--
function dwn(s)
{
document.write(s + "<br/>");
}
//定义一个Point类型
function Point(x,y)
{
this.x = x;
this.y = y;
this.toString = function(){
return "(" + [x,y] + ")";
}
}
//定义一个Vector类型
function Vector(x,y)
{
this.x = x;
this.y = y;
//this.toString = function(){
// return "[" + [x,y] + "]";
//}
}
//这个函数将传入的参数累加到对象的x、y属性上
function add(x, y){
return new this.constructor(this.x + x, this.y + y);
}
var p = new Point(1, 2);
var v = new Vector(-1, 2);
var p1 = add.call(p, 3, 4); //把add函数作为p的方法调用
var v1 = add.apply(v, [3,4]); //把add函数作为v的方法调用
dwn(p1);
dwn(v1);
-->
</script>
</body>
</html>
都是用来调用函数,并指定该次调用的所有者。用法:
方法名.call(调用该方法的对象,参数1,参数2,....)
方法名.apply(调用该方法的对象,[参数1,参数2,....])
这样,在函数中的this对象,将是传入的第一个参数。
<head>
<title>用call和apply调用函数</title>
</head>
<body>
<script>
<!--
function dwn(s)
{
document.write(s + "<br/>");
}
//定义一个Point类型
function Point(x,y)
{
this.x = x;
this.y = y;
this.toString = function(){
return "(" + [x,y] + ")";
}
}
//定义一个Vector类型
function Vector(x,y)
{
this.x = x;
this.y = y;
//this.toString = function(){
// return "[" + [x,y] + "]";
//}
}
//这个函数将传入的参数累加到对象的x、y属性上
function add(x, y){
return new this.constructor(this.x + x, this.y + y);
}
var p = new Point(1, 2);
var v = new Vector(-1, 2);
var p1 = add.call(p, 3, 4); //把add函数作为p的方法调用
var v1 = add.apply(v, [3,4]); //把add函数作为v的方法调用
dwn(p1);
dwn(v1);
-->
</script>
</body>
</html>
都是用来调用函数,并指定该次调用的所有者。用法:
方法名.call(调用该方法的对象,参数1,参数2,....)
方法名.apply(调用该方法的对象,[参数1,参数2,....])
这样,在函数中的this对象,将是传入的第一个参数。
Function.prototype.call(scope,arg1,arg2,arg3....)scope:函数作用域,arg1~argn该方法的n个参数
Function.prototype.apply(scope,[arg1,arg2,arg3....])使用这两种放法通常的目的是为了动态的设置一个函数的作用域,使同一个方法可以作为不同对象的成员方法被调用。
一般来说,推荐使用apply,性能优于call
{
this.showTxt = function(txt)
{
alert(txt);
}
}function Class2()
{
Class1.call(this);
}var c2 = new Class2();c2.showTxt("cc");这样 Class2 就继承Class1了,Class1.call(this) 的 意思就是使用 Class1 对象代替this对象,那么 Class2 中不就有Class1 的所有属性和方法了吗,c2 对象就能够直接调用Class1 的方法以及属性了,执行结果就是:alert(“cc”);
call 和 apply 本身和继承没有关系。在有些框架中,使用call/apply在子类中调用父类的构造方法而已
你可以这样看一下:
alert(c2 instanceof Class1) //false,说明JavaScript并不识别c2是一个Class1