当前位置: 首页 > 图文教程 > 网络编程 > Javascript > javascript教程:call方法

Javascript
玩透弹出窗口
几个常用的日期函数
简单的脚本帮你编排JScript程序中的缩进
得到 words.js?hello,world! 参数的处理方法
如何在javascript中传值
可输入的select
IE支持的HTML元素的DISABLE属性在NETSCAPE4.76中的实现
利用xml数据岛实现多级关联下拉选择框的做法
利用Wipe等ActiveX技术,实现n(n>>2)幅图片轮换擦洗显示
Javascript技术实现真正的网上试听
JavaScript实现在线编辑表格
根据客户端的分辨率不同而重定向到不同网页的脚本
几种不刷新页面取数据的方法
web进度条
随手写的一个动态添加删除行的HTC行为组件
农历与阳历的对照
关于在页面中解决打印的几个问题
"打开,另存为,属性,打印"等14个JS代码
无提示框关闭IE窗口
实现上传(增删)多个文件的客户端写法。

Javascript 中的 javascript教程:call方法


出处:互联网   整理: 软晨网(RuanChen.com)   发布: 2009-09-28   浏览: 99 ::
收藏到网摘: n/a

call 方法
调用一个对象的一个方法,以另一个对象替换当前对象。

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

看懂了没?说实话我没看懂,哈哈,没看懂继续往下看。

call 方法在js继承中经常看到,也一直搞不懂,这到底是什么东西,看下面这段代码:

01.function Person(name,age){
02.  
this.name = name;
03.  
this.age=age;
04.  
this.alertName = function(){
05.   
alert(this.name);
06.  
}
07.  
this.alertAge = function(){
08.   
alert(this.age);
09.  
}
10. 
}
11.
 
12. 
function webDever(name,age,sex){
13.  
Person.call(this,name,age);
14.  
this.sex=sex;
15.  
this.alertSex = function(){
16.   
alert(this.sex);
17.  
}
18. 
}
19. 
var test= new webDever("愚人码头",28,"男");
20. 
test.alertName();//愚人码头
21. 
test.alertAge();//28
22. 
test.alertSex();//男

这样 webDever类就继承Person了,Person.call(this,name,age) 的 意思就是使用 Person对象代替this对象,那么 webDever中不就有Person的所有属性和方法了吗,test对象就能够直接调用Person的方法以及属性了;

说的再明白一点,就是相当于将webDever中的Person.call(this,name,age)这部分代码替换为Person类的:

1.this.name = name;
2.  
this.age=age;
3.  
this.alertName = function(){
4.   
alert(this.name);
5.  
}
6.  
this.alertAge = function(){
7.   
alert(this.age);
8.  
}
这样webDever类就相当于:

01. 
function webDever(name,age,sex){
02.  
this.name = name;
03.  
this.age=age;
04.  
this.alertName = function(){
05.   
alert(this.name);
06.  
}
07.  
this.alertAge = function(){
08.   
alert(this.age);
09.  
}
10.
 
11.  
this.sex=sex;
12.  
this.alertSex = function(){
13.   
alert(this.sex);
14.  
}
15. 
}
16. 
var test= new webDever("愚人码头",28,"男");
17. 
test.alertName();//愚人码头
18. 
test.alertAge();//28
19. 
test.alertSex();//男

不知道能不能这么理解?望大家斧正。

留一个问题:假设webDever类只要继承Person类中的alertName方法,这样可以吗?代码应该怎么写?