首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > 编程 >

个人对call跟apply方法的理解

2012-10-18 
个人对call和apply方法的理解htmlheadscript languagejavascript//定义一个工具类(方法),提供

个人对call和apply方法的理解

<html>   <head>   <script language="javascript">   //定义一个工具"类"(方法),提供具体实现方法,将被很多“类”调用,this将会被使用call或者是apply方法替换——这也是call和apply方法的目的,更换对象function Utils(){this.name = "huangbiao";this.getArgumentsLength = function(str){return arguments.length;}this.getDate = function(){return new Date();}this.getUserName = function(){alert(this.name);}}function User(){this.name = "biaobiao";}//var util = new Utils();var user = new User();//alert(util.getArgumentsLength.call(user,"arg1","arg2","arg3"));//alert(util.getDate.apply(user))//下面这种方法类似于java的“子类调用父类对象方法”util.getUserName();//getUserName方法中的this已经改为user而不再是util,util.getUserName.call(user);</script>   </head>   <body></body>   </html> 

?在自己写插件的时候可以充分利用call和apply的这种特性,但两种方法添加参数的方法是不一致的,分别是逗号和数组

//animal.showName.call(cat,"hb","bb");??
//animal.function_alert.apply(man,["hb","bb","hh"]);

热点排行