技术头条 - 一个快速在微博传播文章的方式     搜索本站
您现在的位置首页 --> JavaScript --> Javascript 中的 call 和 apply

Javascript 中的 call 和 apply

浏览:1404次  出处信息

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. CALL指令有多少种写法    (阅读:1560)
QQ技术交流群:445447336,欢迎加入!
扫一扫订阅我的微信号:IT技术博客大学习
<< 前一篇:javascript插入样式
© 2009 - 2024 by blogread.cn 微博:@IT技术博客大学习

京ICP备15002552号-1