IT技术博客大学习 共学习 共进步
全部 移动开发 后端 数据库 AI 算法 安全 DevOps 前端 设计 开发者

Javascript 中的 call 和 apply

WEB前端开发 2012-02-05 23:10:08 累计浏览 2,429 次
本机暂存

JavaScript 中通过call或者apply用来代替另一个对象调用一个方法,将一个函数的对象上下文从初始的上下文改变为由 thisObj 指定的新对象。简单的说就是改变函数执行的上下文,这是最基本的用法。两个方法基本区别在于传参不同。

  • call(obj,arg1,arg2,arg3);call第一个参数传对象,可以是null。参数以逗号分开进行传值,参数可以是任何类型。
  • apply(obj,[arg1,arg2,arg3]);apply第一个参数传对象,参数可以是数组或者arguments 对象。

这两个方法通常被用来类的继承和回调函数:

作用一、类的继承:

先来看这个例子:

 
01 function Person(name,age){
02   
03 this.name = name;
04   
05 this.age=age;
06   
07 this.alertName = function(){
08   
09 alert(this.name);
10   
11 }
12   
13 this.alertAge = function(){
14   
15 alert(this.age);
16   
17 }
18   
19 }
20   
21 function webDever(name,age,sex){
22   
23 Person.call(this,name,age);
24   
25 this.sex=sex;
26   
27 this.alertSex = function(){
28   
29 alert(this.sex);
30   
31 }
32   
33 }
34   
35 var test= new webDever("愚人码头",28,"男");
36   
37 test.alertName();//愚人码头
38   
39 test.alertAge();//28
40   
41 test.alertSex();//男

这样 webDever类就继承Person类,Person.call(this,name,age) 的 意思就是使用 Person构造函数(也是函数)在this对象下执行,那么 webDever就有了Person的所有属性和方法,test对象就能够直接调用Person的方法以及属性了; 09年的理解解非常粗浅,呵呵。http://www.css88.com/archives/1692

作用二、回调函数:

call 和 apply在回调行数中也非常有用,很多时候我们在开发过程中需要对改变回调函数的执行上下文,最常用的比如ajax或者定时什么的,一般情况下,Ajax都是全局的,也就是window对象下的,来看这个例子:

 
01 function Album(id, title, owner_id) {
02   
03 this.id = id;
04   
05 this.name = title;
06   
07 this.owner_id = owner_id;
08   
09 };
10   
11 Album.prototype.get_owner = function (callback) {
12   
13 var self = this;
14   
15 $.get('/owners/' + this.owner_id, function (data) {
16   
17 callback && callback.call(self, data.name);
18   
19 });
20   
21 };
22   
23 var album = new Album(1, '生活', 2);
24   
25 album.get_owner(function (owner) {
26   
27 alert('The album' + this.name + ' belongs to ' + owner);
28   
29 });

这里

1 album.get_owner(function (owner) {
2   
3 alert('The album' + this.name + ' belongs to ' + owner);
4   
5 });

中的 this.name就能直接取到album对象中的name属性了。

同分类推荐文章

  1. 新特性速递:focus()行为新增focusVisible控制 (2026-05-29 16:23:06)
  2. Algorithmic Theming Engines: Building Self-Correcting Color Systems With `contrast-color()` (2026-05-28 21:00:00)
  3. Revealing Text With CSS letter-spacing (2026-05-27 20:37:33)

查看更多 前端 文章 →

建议继续学习

  1. JQuery实现Excel表格呈现 (累计阅读 48,271)
  2. 深入理解Javascript之执行上下文(Execution Context) (累计阅读 18,281)
  3. 从输入 URL 到页面加载完成的过程中都发生了什么事情? (累计阅读 15,822)
  4. 图片动态局部毛玻璃模糊效果的实现 (累计阅读 14,771)
  5. 天朝第二代身份证号码的验证机制 (累计阅读 14,698)
  6. HTML 5 的data-* 自定义属性 (累计阅读 14,263)
  7. 分享一个JQUERY颜色选择插件 (累计阅读 14,152)
  8. 什么是全栈工程师? (累计阅读 13,959)
  9. 快速排序(Quicksort)的Javascript实现 (累计阅读 11,647)
  10. 7 天打造前端性能监控系统 (累计阅读 11,114)