借用网上的一个例子:
1 fun.call(this,arg1,arg2,arg3)2 3 fun.apply(this,arguments)4 5 this.fun(arg1,arg2,arg3)
三种方法等效。
详细内容这篇博客写的很清楚了,我就偷懒转一下了。
转载:http://www.cnblogs.com/fighting_cp/archive/2010/09/20/1831844.html
下面自己在总结一下自己的领悟:
先贴下代码:
1 2 3 4 5Title 6 7 8 9 10 11 12 13
1 window.meng = window.meng || {}; 2 (function () { 3 4 function Person(name, age, gender) { 5 this._name = name; 6 this._age = age; 7 this._gender = gender; 8 } 9 10 Person.prototype.showInfo = function () {11 console.log("个人"+"\n姓名:" + this._name + "\n年龄:"12 + this._age + "\n性别:" + this._gender);13 };14 15 meng.Person = Person;16 })();
1 window.meng = window.meng || {}; 2 (function () { 3 4 function Student(name,age,gender,num) { 5 meng.Person.apply(this,arguments); 6 this._num=num; 7 } 8 9 Student.prototype=new meng.Person();10 Student.prototype.showInfo=function () {11 console.log("学生"+"\n姓名:" + this._name + "\n年龄:" + 12 this._age + "\n性别:" + this._gender+"\n学号:"+this._num);13 14 };15 meng.Student=Student;16 })();
window.meng = window.meng || {};(function () { function BoyStudent(name,age,num) { meng.Student.call(this,name,age,"female",num); } BoyStudent.prototype = new meng.Student(); BoyStudent.prototype.showInfo=function () { console.log("男学生"+"\n姓名:" + this._name + "\n年龄:" + this._age + "\n性别:" + this._gender+"\n学号:"+this._num); }; meng.BoyStudent=BoyStudent;})();
1 (function () { 2 3 var per1=new meng.Person("Tom",12,"female"); 4 per1.showInfo(); 5 6 var stu1=new meng.Student("lilli",13,"female","001"); 7 stu1.showInfo(); 8 9 var boyStu1=new meng.BoyStudent("David",23,"002");10 boyStu1.showInfo();11 })();
输出结果:
好了,下面开始说明:
(这里说明一下,网上有些人说JS没有继承,但是这里我也写了继承。这也就是我对事物的理解问题,我本来专业学过JAVA,所以对继承了解深刻,而上面JS代码的写法和JAVA里的继承是一个概念,我这里就暂且叫他继承了。主要是理解概念,我感觉没必要死扣这个问题,就如有些人还说JS没有JAVA中的类,但是JS中的函数和JAVA的类也是一个差不多的概念,拿类的概念去理解函数的概念,也无可厚非)
开始说代码,先看下各个函数的参数,(这里帖这几个代码的意义也在于此)。
Person参数有三个name、age、gender这是每个人又具备的属性。
Student参数有有四个,多了个学号num的属性,这是学生所特有的。
BoyStudent参数有三个,同学生类中的三个,只是gender参数默认是female。
大体的结构是BoyStudent继承Student Student继承Person。
BoyStudent继承Student的时候,是三个参数继承四个参数的,顾我用的是call()方法,因为他可以逐个给参数赋值,可以包含不一样的参数。
而Student继承Person的时候,是四个参数继承三个参数的,顾我用的是apply()方法,因为它一下把所有参数搬过来了,简单省事。
当然,call()方法完全可以代替apply()方法,但是能用apply()方法的时候,何必用call()方法逐个去赋值呢。╮(╯▽╰)╭