標籤:
借用網上的一個例子:
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 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>Title</title> 6 <script src="person.js"></script> 7 <script src="student.js"></script> 8 <script src="boyStudent.js"></script> 9 </head>10 <body>11 <script src="main.js"></script>12 </body>13 </html>
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()方法逐個去賦值呢。╮(╯▽╰)╭
js中的apply和call API