Javascript 面向對象編程

fmms 12年前發布 | 81K 次閱讀 JavaScript開發 JavaScript

Javascript 是一個類C的語言,他的面向對象的東西相對于C++/Java 比較奇怪,但是其的確相當的強大,在 Todd 同學的“對象的消息模型”一文中我們已經可以看到一些端倪了。這兩天有個前同事總在問我 Javascript 面向對象的東西,所以,索性寫篇文章讓他看去吧,這里這篇文章主要想從一個整體的角度來說明一下 Javascript 的面向對象的編程。(成文比較倉促,應該有不準確或是有誤的地方,請大家批評指正

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

初探

我們知道 Javascript 中的變量定義基本如下:

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

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

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

于是,我就可以這樣訪問:

//以成員的方式 chenhao.name;
chenhao.email;
chenhao.website;//以 hash map 的方式 chenhao["name"];
chenhao["email"];
chenhao["website"];

關于函數,我們知道 Javascript 的函數是這樣的:

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

于是,我們可以這么干:

var sayHello = function(){
   var hello = "Hello, I'm "+ this.name

            + ", my email is: " + <span style="color:#0000ff;">this</span>.email
            + ", my website is: " + <span style="color:#0000ff;">this</span>.website;

alert (hello); };//直接賦值,這里很像C/C++的函數指針 chenhao.Hello = sayHello; chenhao.Hello ();</pre> </div>

相信這些東西都比較簡單,大家都明白了。 可以看到 javascript 對象函數是直接聲明,直接賦值,直接就用了。runtime 的動態語言。

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

//我們可以看到, 其用 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']

上面的這些例子,我們可以看到這樣幾點:

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

屬性配置 – 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 }
    }
);

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

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

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 = [].slicefunction 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) }
}

參考

來自: coolshell.cn

 本文由用戶 fmms 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!