个人对call和apply方法的理解

来源:互联网 发布:淘宝宝贝违规删除不了 编辑:程序博客网 时间:2024/05/29 03:57
<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"]);

原创粉丝点击