当前位置: 首页 > 图文教程 > 网络编程 > Javascript > 利用javascript中的call实现继承

Javascript
form中限制文本字节数js代码
use jscript with List Proxy Server Information
use jscript List Installed Software
List Installed Software Features
List Information About the Binary Files Used by an Application
List the Codec Files on a Computer
List the UTC Time on a Computer
List Installed Hot Fixes
excel操作之Add Data to a Spreadsheet Cell
Add Formatted Data to a Spreadsheet
Apply an AutoFormat to an Excel Spreadsheet
JavaScript语法着色引擎(demo及打包文件下载)
类之Prototype.js学习
一款JavaScript压缩工具:X2JSCompactor
iis6+javascript Add an Extension File
jscript之Open an Excel Spreadsheet
jscript之Read an Excel Spreadsheet
jscript之List Excel Color Values
去除图像或链接黑眼圈的两种方法总结
Add a Formatted Table to a Word Document

Javascript 中的 利用javascript中的call实现继承


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

昨天阿丹传了一个javascript中的重载例子给我,感觉不错.虽然到现在还是不太明白.怎么实现的.但还是贴出来.
实现setTimeout传object对象
看以下代码实现向里面的function 传参数
<script type="text/javascript">
var _st = window.setTimeout;
window.setTimeout = function(fRef, mDelay) {
if(typeof fRef == 'function'){
var argu = Array.prototype.slice.call(arguments,2);
var f = (function(){ fRef.apply(null, argu); });
return _st(f, mDelay);
}
return _st(fRef,mDelay);
}
function test(x){
alert(x);
}
window.setTimeout(test,1000,'fason');
</script>
call方法JScript参考中的说明:调用一个对象的一个方法,以另一个对象替换当前对象。call([thisObj[,arg1[, arg2[, [,.argN]]]]]),但是没有示例
apply方法JScript参考中的说明:应用某一对象的一个方法,用另一个对象替换当前对象。apply([thisObj[,argArray]])
实际上这两个的作用几乎是相同的,要注意的地方是call(thisObj[,arg1[, arg2[,)中的arg参数可以是变量,而apply([thisObj[,argArray]])中的参数为数组集合。
今早又看到一篇利用call实现继承的例子.呵呵..也一并贴出来.这个例子比较简单.就算是由浅入深吧
<script language="javascript" type="text/javascript">
function father(){//父类
var self=this; //私有变量,子类里不会继承!
var var_private="private variable"; //私有变量
this.var_public="public variable"; //公有变量

this.author="xling";
this.test=function(msg){ //公有方法
alert("该方法位于父类 :" + msg + "\n" + self.author);
}

var test2=function(){ //私有方法,子类不能调用
alert("这个方法是父类的私有方法");
}
}

function father2(){
this.email="xlingFairy#hotmail.com";
}

function suber(){//子类
father.call(this);//通过这一句来继承父类(father)类的可见变量及方法(this)
}

function sun(){
suber.call(this);
father2.call(this);//和上面的一句放在一起,實現多重繼承!爽啊!
}

var mySuber=new suber();
mySuber.test("参数是从子类的实例里传入的");
//mySuber.test2(); //这一句会发生错误码,因为test2是父类的私有类
alert("父类的私有变量,子类不能读取:" + mySuber.var_private);
alert("父类的公有变量,子类可以读取" + mySuber.var_public);

var mySun=new sun();
mySun.test("这个是从孙子级的实例里传入的参数");
alert("父类的私有变量,子类不能读取:" + mySun.var_private);
alert("父类的公有变量,子类可以读取" + mySun.var_public);
alert(mySun.email);
</script>