论坛首页 Web前端技术论坛

通过实例理解javascript 的call()与apply()

浏览 33759 次
精华帖 (0) :: 良好帖 (2) :: 新手帖 (0) :: 隐藏帖 (0)
作者 正文
   发表时间:2010-02-20   最后修改:2010-02-20
先前使用javascript多是为了表单验证,最多是实现客户端的交互功能。基本不用call、apply之类的难懂方法。
现在流行富客户端了。javascript也越来越对象化了。不得不学习一下!

一、方法的定义
call方法:
语法:call([thisObj[,arg1[, arg2[,   [,.argN]]]]])
定义:调用一个对象的一个方法,以另一个对象替换当前对象。
说明:
call 方法可以用来代替另一个对象调用一个方法。call 方法可将一个函数的对象上下文从初始的上下文改变为由 thisObj 指定的新对象。
如果没有提供 thisObj 参数,那么 Global 对象被用作 thisObj。

apply方法:
语法:apply([thisObj[,argArray]])
定义:应用某一对象的一个方法,用另一个对象替换当前对象。
说明:
如果 argArray 不是一个有效的数组或者不是 arguments 对象,那么将导致一个 TypeError。
如果没有提供 argArray 和 thisObj 任何一个参数,那么 Global 对象将被用作 thisObj, 并且无法被传递任何参数。


二、例子程序:
<html>
<head>
<script language="javascript">
/**定义一个animal类*/
function Animal(){
	this.name = "Animal";
	this.showName = function(){
		alert(this.name);
	}
}
/**定义一个Cat类*/
function Cat(){
	this.name = "Cat";
}

/**创建两个类对象*/
var animal = new Animal();
var cat = new Cat();

//通过call或apply方法,将原本属于Animal对象的showName()方法交给当前对象cat来使用了。
//输入结果为"Cat"
animal.showName.call(cat,",");
//animal.showName.apply(cat,[]);
 

</script>
</head>
<body></body>
</html>


以上代码无论是采用animal.showName.call或是animal.showName.apply方法,运行的结果都是输出一个"Cat"的字符串。说明showName方法的调用者被换成了cat对象,而不是最初定义它的animal了。这就是call和apply方法的妙用!

三、小结:
call和apply方法通常被用来实现类似继承一样的功能,以达到代码复用的功效。它们的区别主要体现在参数上。
   发表时间:2010-02-24  
更了解了。thinks
0 请登录后投票
   发表时间:2010-02-25  
看起来蛮有意思的

也很好理解
0 请登录后投票
   发表时间:2010-02-25  
。。。。。。。。。。。你所写的,只是call和apply最基本的作用。根本不是面向对象

你代码的修改版(一般情况已经够用)
<html>  
<head>  
<script language="javascript">  

function Animal(name){  
    this.name = name;  
    this.showName = function(){  
        alert(this.name);  
    }  
}  

function Cat(name){
	Animal.call(this, name);
}  

var cat = new Cat("Black Cat");  

cat.showName();

  
</script>  
</head>  
<body></body>  
</html>  


更完全版
<html>  
<head>  
<script language="javascript">  

function Animal(name){  
    this.name = name;  
    this.showName = function(){  
        alert(this.name);  
    }  
}  

function Cat(name){
	Animal.call(this, name);
}  

Cat.prototype = new Animal();

var cat = new Cat("Black Cat");  

cat.showName();

alert(cat instanceof Animal);

  
</script>  
</head>  
<body></body>  
</html>  


call和apply都是基于this替换。把this的语义转了
0 请登录后投票
   发表时间:2010-02-25  
模拟call, apply的this替换
function Animal(name){  
    this.name = name;  
    this.showName = function(){  
        alert(this.name);  
    };
};

function Cat(name){
	this.superClass = Animal;
	this.superClass(name);
	delete superClass;
}

var cat = new Cat("Black Cat");  

cat.showName();

0 请登录后投票
   发表时间:2010-02-25  
组合->继承->设计模式->创意,lz的路还有很远。。。加油吧
0 请登录后投票
   发表时间:2010-03-01  
to rainsilence:
谢谢! 学习了。正在学习js面对象的知识,交流一下,受益不少!
0 请登录后投票
论坛首页 Web前端技术版

跳转论坛:
Global site tag (gtag.js) - Google Analytics