轉載自Astar先生的Javascript 面向對象編程 |
Javascript 是一個類C的語言,他的面向對象的東西相對於C++/Java 比較奇怪,可是其的確至關的強大,在 Todd 同窗的「對象的消息模型」一文中咱們已經能夠看到一些端倪了。這兩天有個前同事總在問我 Javascript 面向對象的東西,因此,索性寫篇文章讓他看去吧,這裏這篇文章主要想從一個總體的角度來講明一下 Javascript 的面向對象的編程。(成文比較倉促,應該有不許確或是有誤的地方,請你們批評指正)javascript
另,這篇文章主要基於 ECMAScript 5, 旨在介紹新技術。關於兼容性的東西,請看最後一節。html
初探java
咱們知道 Javascript 中的變量定義基本以下:git
- var name = 'Chen Hao';
- var email = 'haoel (@) hotmail.com';
- var website = 'http://coolshell.cn';
若是要用對象來寫的話,就是下面這個樣子:github
- var chenhao = {
- name :'Chen Hao',
- email : 'haoel (@) hotmail.com',
- website : 'http://coolshell.cn'
- };
因而,我就能夠這樣訪問:web
- //以成員的方式
- chenhao.name;
- chenhao.email;
- chenhao.website;
- //以 hash map 的方式
- chenhao["name"];
- chenhao["email"];
- chenhao["website"];
關於函數,咱們知道 Javascript 的函數是這樣的:shell
- var doSomething = function(){
- alert ('Hello World.');
- };
因而,咱們能夠這麼幹:編程
- var sayHello = function(){
- var hello = "Hello, I'm "+ this.name
- + ", my email is: " + this.email
- + ", my website is: " + this.website;
- alert (hello);
- };
- //直接賦值,這裏很像C/C++的函數指針
- chenhao.Hello = sayHello;
- chenhao.Hello ();
相信這些東西都比較簡單,你們都明白了。 能夠看到 javascript 對象函數是直接聲明,直接賦值,直接就用了。runtime 的動態語言。瀏覽器
還有一種比較規範的寫法是:app
- //咱們能夠看到, 其用 function 來作 class。
- var Person = function(name, email, website){
- this.name = name;
- this.email = email;
- this.website = website;
- this.sayHello = function(){
- var hello = "Hello, I'm "+ this.name + ", \n" +
- "my email is: " + this.email + ", \n" +
- "my website is: " + this.website;
- alert (hello);
- };
- };
- var chenhao = new Person ("Chen Hao", "haoel@hotmail.com",
- "http://coolshell.cn");
- chenhao.sayHello ();
順便說一下,要刪除對象的屬性,很簡單:
- delete chenhao['email']
上面的這些例子,咱們能夠看到這樣幾點:
屬性配置 – Object.defineProperty
先看下面的代碼:
- //建立對象
- var chenhao = Object.create (null);
- //設置一個屬性
- Object.defineProperty ( chenhao,
- 'name', { value: 'Chen Hao',
- writable: true,
- configurable: true,
- enumerable: true });
- //設置多個屬性
- Object.defineProperties ( chenhao,
- {
- 'email' : { value: 'haoel@hotmail.com',
- writable: true,
- configurable: true,
- enumerable: true },
- 'website': { value: 'http://coolshell.cn',
- writable: true,
- configurable: true,
- enumerable: true }
- }
- );
下面就說說這些屬性配置是什麼意思。
Get/Set 訪問器
關於 get/set 訪問器,它的意思就是用 get/set 來取代 value(其不能和 value 一塊兒使用),示例以下:
- var age = 0;
- Object.defineProperty ( chenhao,
- 'age', {
- get: function() {return age+1;},
- set: function(value) {age = value;}
- enumerable : true,
- configurable : true
- }
- );
- chenhao.age = 100; //調用 set
- alert (chenhao.age); //調用 get 輸出 101(get 中 +1 了);
咱們再看一個更爲實用的例子——利用已有的屬性(age)經過 get 和 set 構造新的屬性(birth_year):
- Object.defineProperty ( chenhao,
- 'birth_year',
- {
- get: function() {
- var d = new Date ();
- var y = d.getFullYear ();
- return ( y - this.age );
- },
- set: function(year) {
- var d = new Date ();
- var y = d.getFullYear ();
- this.age = y - year;
- }
- }
- );
- alert (chenhao.birth_year);
- chenhao.birth_year = 2000;
- alert (chenhao.age);
這樣作好像有點麻煩,你說,我爲何不寫成下面這個樣子:
- var chenhao = {
- name: "Chen Hao",
- email: "haoel@hotmail.com",
- website: "http://coolshell.cn",
- age: 100,
- get birth_year () {
- var d = new Date ();
- var y = d.getFullYear ();
- return ( y - this.age );
- },
- set birth_year (year) {
- var d = new Date ();
- var y = d.getFullYear ();
- this.age = y - year;
- }
- };
- alert (chenhao.birth_year);
- chenhao.birth_year = 2000;
- alert (chenhao.age);
是的,你的確能夠這樣的,不過經過 defineProperty ()你能夠幹這些事:
1)設置如 writable,configurable,enumerable 等這類的屬性配置。
2)動態地爲一個對象加屬性。好比:一些 HTML 的 DOM 對像。
查看對象屬性配置
若是查看並管理對象的這些配置,下面有個程序能夠輸出對象的屬性和配置等東西:
- //列出對象的屬性.
- function listProperties (obj)
- {
- var newLine = "<br />";
- var names = Object.getOwnPropertyNames (obj);
- for (var i = 0; i < names.length; i++) {
- var prop = names[i];
- document.write (prop + newLine);
- // 列出對象的屬性配置(descriptor)動用 getOwnPropertyDescriptor 函數。
- var descriptor = Object.getOwnPropertyDescriptor (obj, prop);
- for (var attr in descriptor) {
- document.write ("..." + attr + ': ' + descriptor[attr]);
- document.write (newLine);
- }
- document.write (newLine);
- }
- }
- listProperties (chenhao);
call,apply, bind 和 this
關於 Javascript 的 this 指針,和C++/Java 很相似。 咱們來看個示例:(這個示例很簡單了,我就很少說了)
- function print (text){
- document.write (this.value + ' - ' + text+ '<br>');
- }
- var a = {value: 10, print : print};
- var b = {value: 20, print : print};
- print ('hello');// this => global, output "undefined - hello"
- a.print ('a');// this => a, output "10 - a"
- b.print ('b'); // this => b, output "20 - b"
- a['print']('a'); // this => a, output "10 - a"
咱們再來看看 call 和 apply,這兩個函數的差異就是參數的樣子不同,另外一個就是性能不同,apply 的性能要差不少。(關於性能,可到 JSPerf 上去跑跑看看)
- print.call (a, 'a'); // this => a, output "10 - a"
- print.call (b, 'b'); // this => b, output "20 - b"
- print.apply (a, ['a']); // this => a, output "10 - a"
- print.apply (b, ['b']); // this => b, output "20 - b"
可是在 bind 後,this 指針,可能會有不同,可是由於 Javascript 是動態的。以下面的示例
- var p = print.bind (a);
- p('a'); // this => a, output "10 - a"
- p.call (b, 'b'); // this => a, output "10 - b"
- p.apply (b, ['b']); // this => a, output "10 - b"
繼承和重載
經過上面的那些示例,咱們能夠經過 Object.create ()來實際繼承,請看下面的代碼,Student 繼承於 Object。
- var Person = Object.create (null);
- Object.defineProperties
- (
- Person,
- {
- 'name' : { value: 'Chen Hao'},
- 'email' : { value : 'haoel@hotmail.com'},
- 'website': { value: 'http://coolshell.cn'}
- }
- );
- Person.sayHello = function () {
- var hello = "<p>Hello, I am "+ this.name + ", <br>" +
- "my email is: " + this.email + ", <br>" +
- "my website is: " + this.website;
- document.write (hello + "<br>");
- }
- var Student = Object.create (Person);
- Student.no = "1234567"; //學號
- Student.dept = "Computer Science"; //系
- //使用 Person 的屬性
- document.write (Student.name + ' ' + Student.email + ' ' + Student.website +'<br>');
- //使用 Person 的方法
- Student.sayHello ();
- //重載 SayHello 方法
- Student.sayHello = function (person) {
- var hello = "<p>Hello, I am "+ this.name + ", <br>" +
- "my email is: " + this.email + ", <br>" +
- "my website is: " + this.website + ", <br>" +
- "my student no is: " + this. no + ", <br>" +
- "my departent is: " + this. dept;
- document.write (hello + '<br>');
- }
- //再次調用
- Student.sayHello ();
- //查看 Student 的屬性(只有 no 、 dept 和重載了的 sayHello)
- document.write ('<p>' + Object.keys (Student) + '<br>');
通用上面這個示例,咱們能夠看到,Person 裏的屬性並無被真正複製到了 Student 中來,可是咱們能夠去存取。這是由於 Javascript 用委託實現了這一機制。其實,這就是 Prototype,Person 是 Student 的 Prototype。
當咱們的代碼須要一個屬性的時候,Javascript 的引擎會先看當前的這個對象中是否有這個屬性,若是沒有的話,就會查找他的 Prototype 對象是否有這個屬性,一直繼續下去,直到找到或是直到沒有 Prototype 對象。
爲了證實這個事,咱們可使用 Object.getPrototypeOf ()來檢驗一下:
- Student.name = 'aaa';
- //輸出 aaa
- document.write ('<p>' + Student.name + '</p>');
- //輸出 Chen Hao
- document.write ('<p>' +Object.getPrototypeOf (Student) .name + '</p>');
因而,你還能夠在子對象的函數裏調用父對象的函數,就好像 C++ 裏的 Base::func () 同樣。因而,咱們重載 hello 的方法就可使用父類的代碼了,以下所示:
- //新版的重載 SayHello 方法
- Student.sayHello = function (person) {
- Object.getPrototypeOf (this) .sayHello.call (this);
- var hello = "my student no is: " + this. no + ", <br>" +
- "my departent is: " + this. dept;
- document.write (hello + '<br>');
- }
這個很強大吧。
組合
上面的那個東西還不能知足咱們的要求,咱們可能但願這些對象能真正的組合起來。爲何要組合?由於咱們都知道是這是 OO 設計的最重要的東西。不過,這對於 Javascript 來並無支持得特別好,很差咱們依然能夠搞定個事。
首先,咱們須要定義一個 Composition 的函數:(target 是做用因而對象,source 是源對象),下面這個代碼仍是很簡單的,就是把 source 裏的屬性一個一個拿出來而後定義到 target 中。
- function Composition (target, source)
- {
- var desc = Object.getOwnPropertyDescriptor;
- var prop = Object.getOwnPropertyNames;
- var def_prop = Object.defineProperty;
- prop (source) .forEach (
- function(key) {
- def_prop (target, key, desc (source, key))
- }
- )
- return target;
- }
有了這個函數之後,咱們就能夠這來玩了:
- //藝術家
- var Artist = Object.create (null);
- Artist.sing = function() {
- return this.name + ' starts singing...';
- }
- Artist.paint = function() {
- return this.name + ' starts painting...';
- }
- //運動員
- var Sporter = Object.create (null);
- Sporter.run = function() {
- return this.name + ' starts running...';
- }
- Sporter.swim = function() {
- return this.name + ' starts swimming...';
- }
- Composition (Person, Artist);
- document.write (Person.sing () + '<br>');
- document.write (Person.paint () + '<br>');
- Composition (Person, Sporter);
- document.write (Person.run () + '<br>');
- document.write (Person.swim () + '<br>');
- //看看 Person 中有什麼?(輸出:sayHello,sing,paint,swim,run)
- document.write ('<p>' + Object.keys (Person) + '<br>');
Prototype 和繼承
咱們先來講說 Prototype。咱們先看下面的例程,這個例程不須要解釋吧,很像C語言裏的函數指針,在C語言裏這樣的東西見得多了。
- var plus = function(x,y){
- document.write ( x + ' + ' + y + ' = ' + (x+y) + '<br>');
- return x + y;
- };
- var minus = function(x,y){
- document.write (x + ' - ' + y + ' = ' + (x-y) + '<br>');
- return x - y;
- };
- var operations = {
- '+': plus,
- '-': minus
- };
- var calculate = function(x, y, operation){
- return operations[operation](x, y);
- };
- calculate (12, 4, '+');
- calculate (24, 3, '-');
那麼,咱們能不能把這些東西封裝起來呢,咱們須要使用 prototype。看下面的示例:
- var Cal = function(x, y){
- this.x = x;
- this.y = y;
- }
- Cal.prototype.operations = {
- '+': function(x, y) { return x+y;},
- '-': function(x, y) { return x-y;}
- };
- Cal.prototype.calculate = function(operation){
- return this.operations[operation](this.x, this.y);
- };
- var c = new Cal (4, 5);
- Cal.calculate ('+');
- Cal.calculate ('-');
這就是 prototype 的用法,prototype 是 javascript 這個語言中最重要的內容。網上有太多的文章介始這個東西了。說白了,prototype 就是對一對象進行擴展,其特色在於經過「複製」一個已經存在的實例來返回新的實例,而不是新建實例。被複制的實例就是咱們所稱的「原型」,這個原型是可定 制的(固然,這裏沒有真正的複製,實際只是委託)。上面的這個例子中,咱們擴展了實例 Cal,讓其有了一個 operations 的屬性和一個 calculate 的方法。
這樣,咱們能夠經過這一特性來實現繼承。還記得咱們最最前面的那個 Person 吧, 下面的示例是建立一個 Student 來繼承 Person。
- function Person (name, email, website){
- this.name = name;
- this.email = email;
- this.website = website;
- };
- Person.prototype.sayHello = function(){
- var hello = "Hello, I am "+ this.name + ", <br>" +
- "my email is: " + this.email + ", <br>" +
- "my website is: " + this.website;
- return hello;
- };
- function Student (name, email, website, no, dept){
- var proto = Object.getPrototypeOf;
- proto (Student.prototype) .constructor.call (this, name, email, website);
- this.no = no;
- this.dept = dept;
- }
- // 繼承 prototype
- Student.prototype = Object.create (Person.prototype);
- //重置構造函數
- Student.prototype.constructor = Student;
- //重載 sayHello ()
- Student.prototype.sayHello = function(){
- var proto = Object.getPrototypeOf;
- var hello = proto (Student.prototype) .sayHello.call (this) + '<br>';
- hello += "my student no is: " + this. no + ", <br>" +
- "my departent is: " + this. dept;
- return hello;
- };
- var me = new Student (
- "Chen Hao",
- "haoel@hotmail.com",
- "http://coolshell.cn",
- "12345678",
- "Computer Science"
- );
- document.write (me.sayHello ());
兼容性
上面的這些代碼並不必定能在全部的瀏覽器下都能運行,由於上面這些代碼遵循 ECMAScript 5 的規範,關於 ECMAScript 5 的瀏覽器兼容列表,你能夠看這裏「ES5瀏覽器兼容表」。
本文中的全部代碼都在 Chrome 最新版中測試過了。
下面是一些函數,能夠用在不兼容 ES5 的瀏覽器中:
Object.create ()函數
- function clone (proto) {
- function Dummy () { }
- Dummy.prototype = proto;
- Dummy.prototype.constructor = Dummy;
- return new Dummy (); //等價於 Object.create (Person);
- }
- var me = clone (Person);
defineProperty ()函數
- function defineProperty (target, key, descriptor) {
- if (descriptor.value){
- target[key] = descriptor.value;
- }else {
- descriptor.get && target.__defineGetter__(key, descriptor.get);
- descriptor.set && target.__defineSetter__(key, descriptor.set);
- }
- return target
- }
keys ()函數
- function keys (object) { var result, key
- result = [];
- for (key in object){
- if (object.hasOwnProperty (key)) result.push (key)
- }
- return result;
- }
Object.getPrototypeOf () 函數
- function proto (object) {
- return !object? null
- : '__proto__' in object? object.__proto__
- : /* not exposed? */ object.constructor.prototype
- }
bind 函數
- var slice = [].slice
- function bind (fn, bound_this) { var bound_args
- bound_args = slice.call (arguments, 2)
- return function() { var args
- args = bound_args.concat (slice.call (arguments))
- return fn.apply (bound_this, args) }
- }