Javascript 面向對象編程

  轉載自Astar先生的Javascript 面向對象編程

Javascript 是一個類C的語言,他的面向對象的東西相對於C++/Java 比較奇怪,可是其的確至關的強大,在 Todd 同窗的「對象的消息模型」一文中咱們已經能夠看到一些端倪了。這兩天有個前同事總在問我 Javascript 面向對象的東西,因此,索性寫篇文章讓他看去吧,這裏這篇文章主要想從一個總體的角度來講明一下 Javascript 的面向對象的編程。(成文比較倉促,應該有不許確或是有誤的地方,請你們批評指正javascript

另,這篇文章主要基於 ECMAScript 5, 旨在介紹新技術。關於兼容性的東西,請看最後一節。html

初探java

咱們知道 Javascript 中的變量定義基本以下:git

  
  
           
  
  
  1. var name = 'Chen Hao'
  2. var email = 'haoel (@) hotmail.com'
  3. var website = 'http://coolshell.cn'

若是要用對象來寫的話,就是下面這個樣子:github

  
  
           
  
  
  1. var chenhao = { 
  2.       name :'Chen Hao'
  3.       email : 'haoel (@) hotmail.com'
  4.       website : 'http://coolshell.cn' 
  5. }; 

因而,我就能夠這樣訪問:web

  
  
           
  
  
  1. //以成員的方式 
  2. chenhao.name; 
  3. chenhao.email; 
  4. chenhao.website; 
  5. //以 hash map 的方式 
  6. chenhao["name"]; 
  7. chenhao["email"]; 
  8. chenhao["website"]; 

關於函數,咱們知道 Javascript 的函數是這樣的:shell

  
  
           
  
  
  1. var doSomething = function(){ 
  2.    alert ('Hello World.'); 
  3. };  

因而,咱們能夠這麼幹:編程

  
  
           
  
  
  1. var sayHello = function(){ 
  2.    var hello = "Hello, I'm "this.name 
  3.                 + ", my email is: " + this.email 
  4.                 + ", my website is: " + this.website; 
  5.    alert (hello); 
  6. }; 
  7. //直接賦值,這裏很像C/C++的函數指針 
  8. chenhao.Hello = sayHello; 
  9. chenhao.Hello (); 

相信這些東西都比較簡單,你們都明白了。 能夠看到 javascript 對象函數是直接聲明,直接賦值,直接就用了。runtime 的動態語言。瀏覽器

還有一種比較規範的寫法是:app

  
  
           
  
  
  1. //咱們能夠看到, 其用 function 來作 class。 
  2. var Person = function(name, email, website){ 
  3.     this.name = name; 
  4.     this.email = email; 
  5.     this.website = website; 
  6.     this.sayHello = function(){ 
  7.         var hello = "Hello, I'm "this.name  + ", \n" + 
  8.                     "my email is: " + this.email + ", \n" + 
  9.                     "my website is: " + this.website; 
  10.         alert (hello); 
  11.     }; 
  12. }; 
  13. var chenhao = new Person ("Chen Hao""haoel@hotmail.com"
  14.                                      "http://coolshell.cn"); 
  15. chenhao.sayHello (); 

順便說一下,要刪除對象的屬性,很簡單:

  
  
           
  
  
  1. delete chenhao['email'

上面的這些例子,咱們能夠看到這樣幾點:

  1. Javascript 的數據和成員封裝很簡單。沒有類徹底是對象操做。純動態!
  2. Javascript function 中的 this 指針很關鍵,若是沒有的話,那就是局部變量或局部函數。
  3. Javascript 對象成員函數能夠在使用時臨時聲明,並把一個全局函數直接賦過去就行了。
  4. Javascript 的成員函數能夠在實例上進行修改,也就是說不一樣實例相同函數名的行爲不必定同樣。

屬性配置 – Object.defineProperty

先看下面的代碼:

  
  
           
  
  
  1. //建立對象 
  2. var chenhao = Object.create (null); 
  3. //設置一個屬性 
  4. Object.defineProperty ( chenhao, 
  5.                 'name', { value:  'Chen Hao'
  6.                           writable:     true
  7.                           configurable: true
  8.                           enumerable:   true }); 
  9. //設置多個屬性 
  10. Object.defineProperties ( chenhao, 
  11.     { 
  12.         'email'  : { value:  'haoel@hotmail.com'
  13.                      writable:     true
  14.                      configurable: true
  15.                      enumerable:   true }, 
  16.         'website': { value: 'http://coolshell.cn'
  17.                      writable:     true
  18.                      configurable: true
  19.                      enumerable:   true } 
  20.     } 
  21. ); 

下面就說說這些屬性配置是什麼意思。

  • writable:這個屬性的值是否能夠改。
  • configurable:這個屬性的配置是否能夠改。
  • enumerable:這個屬性是否能在 for…in 循環中遍歷出來或在 Object.keys 中列舉出來。
  • value:屬性值。
  • get ()/set (_value):get 和 set 訪問器。

Get/Set 訪問器

  關於 get/set 訪問器,它的意思就是用 get/set 來取代 value(其不能和 value 一塊兒使用),示例以下:

  
  
           
  
  
  1. var  age = 0; 
  2. Object.defineProperty ( chenhao, 
  3.             'age', { 
  4.                       get: function() {return age+1;}, 
  5.                       set: function(value) {age = value;} 
  6.                       enumerable : true
  7.                       configurable : true 
  8.                     } 
  9. ); 
  10. chenhao.age = 100; //調用 set 
  11. alert (chenhao.age); //調用 get 輸出 101(get 中 +1 了); 

  咱們再看一個更爲實用的例子——利用已有的屬性(age)經過 get 和 set 構造新的屬性(birth_year):

  
  
           
  
  
  1. Object.defineProperty ( chenhao, 
  2.             'birth_year'
  3.             { 
  4.                 get: function() { 
  5.                     var d = new Date (); 
  6.                     var y = d.getFullYear (); 
  7.                     return ( y - this.age ); 
  8.                 }, 
  9.                 set: function(year) { 
  10.                     var d = new Date (); 
  11.                     var y = d.getFullYear (); 
  12.                     this.age = y - year; 
  13.                 } 
  14.             } 
  15. ); 
  16. alert (chenhao.birth_year); 
  17. chenhao.birth_year = 2000; 
  18. alert (chenhao.age); 

  這樣作好像有點麻煩,你說,我爲何不寫成下面這個樣子:

  
  
           
  
  
  1. var chenhao = { 
  2.     name: "Chen Hao"
  3.     email: "haoel@hotmail.com"
  4.     website: "http://coolshell.cn"
  5.     age: 100, 
  6.     get birth_year () { 
  7.         var d = new Date (); 
  8.         var y = d.getFullYear (); 
  9.         return ( y - this.age ); 
  10.     }, 
  11.     set birth_year (year) { 
  12.         var d = new Date (); 
  13.         var y = d.getFullYear (); 
  14.         this.age = y - year; 
  15.     } 
  16. }; 
  17. alert (chenhao.birth_year); 
  18. chenhao.birth_year = 2000; 
  19. alert (chenhao.age); 

  是的,你的確能夠這樣的,不過經過 defineProperty ()你能夠幹這些事:

  1)設置如 writable,configurable,enumerable 等這類的屬性配置。

  2)動態地爲一個對象加屬性。好比:一些 HTML 的 DOM 對像。

  查看對象屬性配置

  若是查看並管理對象的這些配置,下面有個程序能夠輸出對象的屬性和配置等東西:

  
  
           
  
  
  1. //列出對象的屬性. 
  2. function listProperties (obj) 
  3.     var newLine = "<br />"
  4.     var names = Object.getOwnPropertyNames (obj); 
  5.     for (var i = 0; i < names.length; i++) { 
  6.         var prop = names[i]; 
  7.         document.write (prop + newLine); 
  8.         // 列出對象的屬性配置(descriptor)動用 getOwnPropertyDescriptor 函數。 
  9.         var descriptor = Object.getOwnPropertyDescriptor (obj, prop); 
  10.         for (var attr in descriptor) { 
  11.             document.write ("..." + attr + ': ' + descriptor[attr]); 
  12.             document.write (newLine); 
  13.         } 
  14.         document.write (newLine); 
  15.     } 
  16. listProperties (chenhao); 

  call,apply, bind 和 this

  關於 Javascript 的 this 指針,和C++/Java 很相似。 咱們來看個示例:(這個示例很簡單了,我就很少說了)

  
  
           
  
  
  1. function print (text){ 
  2.     document.write (this.value + ' - ' + text+ '<br>'); 
  3. var a = {value: 10, print : print}; 
  4. var b = {value: 20, print : print}; 
  5. print ('hello');// this => global, output "undefined - hello" 
  6. a.print ('a');// this => a, output "10 - a" 
  7. b.print ('b'); // this => b, output "20 - b" 
  8. a['print']('a'); // this => a, output "10 - a" 

  咱們再來看看 call 和 apply,這兩個函數的差異就是參數的樣子不同,另外一個就是性能不同,apply 的性能要差不少。(關於性能,可到 JSPerf 上去跑跑看看)

  
  
           
  
  
  1. print.call (a, 'a'); // this => a, output "10 - a" 
  2. print.call (b, 'b'); // this => b, output "20 - b" 
  3. print.apply (a, ['a']); // this => a, output "10 - a" 
  4. print.apply (b, ['b']); // this => b, output "20 - b" 

  可是在 bind 後,this 指針,可能會有不同,可是由於 Javascript 是動態的。以下面的示例

  
  
           
  
  
  1. var p = print.bind (a); 
  2. p('a');             // this => a, output "10 - a" 
  3. p.call (b, 'b');     // this => a, output "10 - b" 
  4. p.apply (b, ['b']);  // this => a, output "10 - b" 

  繼承和重載

  經過上面的那些示例,咱們能夠經過 Object.create ()來實際繼承,請看下面的代碼,Student 繼承於 Object。

  
  
           
  
  
  1. var Person = Object.create (null); 
  2. Object.defineProperties 
  3.     Person, 
  4.     { 
  5.         'name'  : {  value: 'Chen Hao'}, 
  6.         'email'  : { value : 'haoel@hotmail.com'}, 
  7.         'website': { value: 'http://coolshell.cn'
  8.     } 
  9. ); 
  10. Person.sayHello = function () { 
  11.     var hello = "<p>Hello, I am "this.name  + ", <br>" + 
  12.                 "my email is: " + this.email + ", <br>" + 
  13.                 "my website is: " + this.website; 
  14.     document.write (hello + "<br>"); 
  15. var Student = Object.create (Person); 
  16. Student.no = "1234567"//學號 
  17. Student.dept = "Computer Science"//系 
  18. //使用 Person 的屬性 
  19. document.write (Student.name + ' ' + Student.email + ' ' + Student.website +'<br>'); 
  20. //使用 Person 的方法 
  21. Student.sayHello (); 
  22. //重載 SayHello 方法 
  23. Student.sayHello = function (person) { 
  24.     var hello = "<p>Hello, I am "this.name  + ", <br>" + 
  25.                 "my email is: " + this.email + ", <br>" + 
  26.                 "my website is: " + this.website + ", <br>" + 
  27.                 "my student no is: " + this. no + ", <br>" + 
  28.                 "my departent is: " + this. dept; 
  29.     document.write (hello + '<br>'); 
  30. //再次調用 
  31. Student.sayHello (); 
  32. //查看 Student 的屬性(只有 no 、 dept 和重載了的 sayHello) 
  33. document.write ('<p>' + Object.keys (Student) + '<br>'); 

  通用上面這個示例,咱們能夠看到,Person 裏的屬性並無被真正複製到了 Student 中來,可是咱們能夠去存取。這是由於 Javascript 用委託實現了這一機制。其實,這就是 Prototype,Person 是 Student 的 Prototype。

  當咱們的代碼須要一個屬性的時候,Javascript 的引擎會先看當前的這個對象中是否有這個屬性,若是沒有的話,就會查找他的 Prototype 對象是否有這個屬性,一直繼續下去,直到找到或是直到沒有 Prototype 對象。

  爲了證實這個事,咱們可使用 Object.getPrototypeOf ()來檢驗一下:

  
  
           
  
  
  1. Student.name = 'aaa'
  2. //輸出 aaa 
  3. document.write ('<p>' + Student.name + '</p>'); 
  4. //輸出 Chen Hao 
  5. document.write ('<p>' +Object.getPrototypeOf (Student) .name + '</p>'); 

  因而,你還能夠在子對象的函數裏調用父對象的函數,就好像 C++ 裏的 Base::func () 同樣。因而,咱們重載 hello 的方法就可使用父類的代碼了,以下所示:

  
  
           
  
  
  1. //新版的重載 SayHello 方法 
  2. Student.sayHello = function (person) { 
  3.     Object.getPrototypeOf (this) .sayHello.call (this); 
  4.     var hello = "my student no is: " + this. no + ", <br>" + 
  5.                 "my departent is: " + this. dept; 
  6.     document.write (hello + '<br>'); 

  這個很強大吧。

  組合

  上面的那個東西還不能知足咱們的要求,咱們可能但願這些對象能真正的組合起來。爲何要組合?由於咱們都知道是這是 OO 設計的最重要的東西。不過,這對於 Javascript 來並無支持得特別好,很差咱們依然能夠搞定個事。

  首先,咱們須要定義一個 Composition 的函數:(target 是做用因而對象,source 是源對象),下面這個代碼仍是很簡單的,就是把 source 裏的屬性一個一個拿出來而後定義到 target 中。

  
  
           
  
  
  1. function Composition (target, source) 
  2.     var desc  = Object.getOwnPropertyDescriptor; 
  3.     var prop  = Object.getOwnPropertyNames; 
  4.     var def_prop = Object.defineProperty; 
  5.     prop (source) .forEach ( 
  6.         function(key) { 
  7.             def_prop (target, key, desc (source, key)) 
  8.         } 
  9.     ) 
  10.     return target; 

  有了這個函數之後,咱們就能夠這來玩了:

  
  
           
  
  
  1. //藝術家 
  2. var Artist = Object.create (null); 
  3. Artist.sing = function() { 
  4.     return this.name + ' starts singing...'
  5. Artist.paint = function() { 
  6.     return this.name + ' starts painting...'
  7. //運動員 
  8. var Sporter = Object.create (null); 
  9. Sporter.run = function() { 
  10.     return this.name + ' starts running...'
  11. Sporter.swim = function() { 
  12.     return this.name + ' starts swimming...'
  13. Composition (Person, Artist); 
  14. document.write (Person.sing () + '<br>'); 
  15. document.write (Person.paint () + '<br>'); 
  16. Composition (Person, Sporter); 
  17. document.write (Person.run () + '<br>'); 
  18. document.write (Person.swim () + '<br>'); 
  19. //看看 Person 中有什麼?(輸出:sayHello,sing,paint,swim,run) 
  20. document.write ('<p>' + Object.keys (Person) + '<br>'); 

  Prototype 和繼承

  咱們先來講說 Prototype。咱們先看下面的例程,這個例程不須要解釋吧,很像C語言裏的函數指針,在C語言裏這樣的東西見得多了。

  
  
           
  
  
  1. var plus = function(x,y){ 
  2.     document.write ( x + ' + ' + y + ' = ' + (x+y) + '<br>'); 
  3.     return x + y; 
  4. }; 
  5. var minus = function(x,y){ 
  6.     document.write (x + ' - ' + y + ' = ' + (x-y) + '<br>'); 
  7.     return x - y; 
  8. }; 
  9. var operations = { 
  10.     '+': plus, 
  11.     '-': minus 
  12. }; 
  13. var calculate = function(x, y, operation){ 
  14.     return operations[operation](x, y); 
  15. }; 
  16. calculate (12, 4, '+'); 
  17. calculate (24, 3, '-'); 

  那麼,咱們能不能把這些東西封裝起來呢,咱們須要使用 prototype。看下面的示例:

  
  
           
  
  
  1. var Cal = function(x, y){ 
  2.     this.x = x; 
  3.     this.y = y; 
  4. Cal.prototype.operations = { 
  5.     '+'function(x, y) { return x+y;}, 
  6.     '-'function(x, y) { return x-y;} 
  7. }; 
  8. Cal.prototype.calculate = function(operation){ 
  9.     return this.operations[operation](this.x, this.y); 
  10. }; 
  11. var c = new Cal (4, 5); 
  12. Cal.calculate ('+'); 
  13. Cal.calculate ('-'); 

  這就是 prototype 的用法,prototype 是 javascript 這個語言中最重要的內容。網上有太多的文章介始這個東西了。說白了,prototype 就是對一對象進行擴展,其特色在於經過「複製」一個已經存在的實例來返回新的實例,而不是新建實例。被複制的實例就是咱們所稱的「原型」,這個原型是可定 制的(固然,這裏沒有真正的複製,實際只是委託)。上面的這個例子中,咱們擴展了實例 Cal,讓其有了一個 operations 的屬性和一個 calculate 的方法。

  這樣,咱們能夠經過這一特性來實現繼承。還記得咱們最最前面的那個 Person 吧, 下面的示例是建立一個 Student 來繼承 Person。

  
  
           
  
  
  1. function Person (name, email, website){ 
  2.     this.name = name; 
  3.     this.email = email; 
  4.     this.website = website; 
  5. }; 
  6. Person.prototype.sayHello = function(){ 
  7.     var hello = "Hello, I am "this.name  + ", <br>" + 
  8.                 "my email is: " + this.email + ", <br>" + 
  9.                 "my website is: " + this.website; 
  10.     return hello; 
  11. }; 
  12. function Student (name, email, website, no, dept){ 
  13.     var proto = Object.getPrototypeOf; 
  14.     proto (Student.prototype) .constructor.call (this, name, email, website); 
  15.     this.no = no; 
  16.     this.dept = dept; 
  17. // 繼承 prototype 
  18. Student.prototype = Object.create (Person.prototype); 
  19. //重置構造函數 
  20. Student.prototype.constructor = Student; 
  21. //重載 sayHello () 
  22. Student.prototype.sayHello = function(){ 
  23.     var proto = Object.getPrototypeOf; 
  24.     var hello = proto (Student.prototype) .sayHello.call (this) + '<br>'
  25.     hello += "my student no is: " + this. no + ", <br>" + 
  26.              "my departent is: " + this. dept; 
  27.     return hello; 
  28. }; 
  29. var me = new Student ( 
  30.     "Chen Hao"
  31.     "haoel@hotmail.com"
  32.     "http://coolshell.cn"
  33.     "12345678"
  34.     "Computer Science" 
  35. ); 
  36. document.write (me.sayHello ()); 

  兼容性

  上面的這些代碼並不必定能在全部的瀏覽器下都能運行,由於上面這些代碼遵循 ECMAScript 5 的規範,關於 ECMAScript 5 的瀏覽器兼容列表,你能夠看這裏「ES5瀏覽器兼容表」。

  本文中的全部代碼都在 Chrome 最新版中測試過了。

  下面是一些函數,能夠用在不兼容 ES5 的瀏覽器中:

  Object.create ()函數

  
  
           
  
  
  1. function clone (proto) { 
  2.     function Dummy () { } 
  3.     Dummy.prototype             = proto; 
  4.     Dummy.prototype.constructor = Dummy; 
  5.     return new Dummy (); //等價於 Object.create (Person); 
  6. var me = clone (Person); 

  defineProperty ()函數

  
  
           
  
  
  1. function defineProperty (target, key, descriptor) { 
  2.     if (descriptor.value){ 
  3.         target[key] = descriptor.value; 
  4.     }else { 
  5.         descriptor.get && target.__defineGetter__(key, descriptor.get); 
  6.         descriptor.set && target.__defineSetter__(key, descriptor.set); 
  7.     } 
  8.     return target 

  keys ()函數

  
  
           
  
  
  1. function keys (object) { var result, key 
  2.     result = []; 
  3.     for (key in object){ 
  4.         if (object.hasOwnProperty (key))  result.push (key) 
  5.     } 
  6.     return result; 

  Object.getPrototypeOf () 函數

  
  
           
  
  
  1. function proto (object) { 
  2.     return !object?                null 
  3.          : '__proto__' in object?  object.__proto__ 
  4.          : /* not exposed? */      object.constructor.prototype 

  bind 函數

  
  
           
  
  
  1. var slice = [].slice 
  2. function bind (fn, bound_this) { var bound_args 
  3.     bound_args = slice.call (arguments, 2) 
  4.     return function() { var args 
  5.         args = bound_args.concat (slice.call (arguments)) 
  6.         return fn.apply (bound_this, args) } 
相關文章
相關標籤/搜索