JavaScript繼承詳解(四)

來源:互聯網
上載者:User

 

在本章中,我們將分析Douglas Crockford關於JavaScript繼承的一個實現 - Classical Inheritance in JavaScript。 Crockford是JavaScript開發社區最知名的權威,是JSON、JSLint、JSMin和ADSafe之父,是《JavaScript: The Good Parts》的作者。 現在是Yahoo的資深JavaScript架構師,參與YUI的設計開發。 這裡有一篇文章詳細介紹了Crockford的生平和著作。 當然Crockford也是我等小輩崇拜的對象。

調用方式

首先讓我們看下使用Crockford式繼承的調用方式: 注意:代碼中的method、inherits、uber都是自訂的對象,我們會在後面的程式碼分析中詳解。

        // 定義Person類        function Person(name) {            this.name = name;        }        // 定義Person的原型方法        Person.method("getName", function() {            return this.name;        });                  // 定義Employee類        function Employee(name, employeeID) {            this.name = name;            this.employeeID = employeeID;        }        // 指定Employee類從Person類繼承        Employee.inherits(Person);        // 定義Employee的原型方法        Employee.method("getEmployeeID", function() {            return this.employeeID;        });        Employee.method("getName", function() {            // 注意,可以在子類中調用父類的原型方法            return "Employee name: " + this.uber("getName");        });        // 執行個體化子類        var zhang = new Employee("ZhangSan", "1234");        console.log(zhang.getName());   // "Employee name: ZhangSan"        

 

這裡面有幾處不得不提的硬傷:

  • 子類從父類繼承的代碼必須在子類和父類都定義好之後進行,並且必須在子類原型方法定義之前進行。
  • 雖然子類方法體中可以調用父類的方法,但是子類的建構函式無法調用父類的建構函式。
  • 代碼的書寫不夠優雅,比如原型方法的定義以及調用父類的方法(不直觀)。

 

當然Crockford的實現還支援子類中的方法調用帶參數的父類方法,如下例子:

        function Person(name) {            this.name = name;        }        Person.method("getName", function(prefix) {            return prefix + this.name;        });        function Employee(name, employeeID) {            this.name = name;            this.employeeID = employeeID;        }        Employee.inherits(Person);        Employee.method("getName", function() {            // 注意,uber的第一個參數是要調用父類的函數名稱,後面的參數都是此函數的參數            // 個人覺得這樣方式不如這樣調用來的直觀:this.uber("Employee name: ")            return this.uber("getName", "Employee name: ");        });        var zhang = new Employee("ZhangSan", "1234");        console.log(zhang.getName());   // "Employee name: ZhangSan"        

 

程式碼分析

首先method函數的定義就很簡單了:

        Function.prototype.method = function(name, func) {            // this指向當前函數,也即是typeof(this) === "function"            this.prototype[name] = func;            return this;        };        

要特別注意這裡this的指向。當我們看到this時,不能僅僅關注於當前函數,而應該想到當前函數的調用方式。 比如這個例子中的method我們不會通過new的方式調用,所以method中的this指向的是當前函數。

 

inherits函數的定義有點複雜:

        Function.method('inherits', function (parent) {            // 關鍵是這一段:this.prototype = new parent(),這裡實現了原型的引用            var d = {}, p = (this.prototype = new parent());                        // 只為子類的原型增加uber方法,這裡的Closure是為了在調用uber函數時知道當前類的父類的原型(也即是變數 - v)            this.method('uber', function uber(name) {                // 這裡考慮到如果name是存在於Object.prototype中的函數名的情況                // 比如 "toString" in {} === true                if (!(name in d)) {                    // 通過d[name]計數,不理解具體的含義                    d[name] = 0;                }                        var f, r, t = d[name], v = parent.prototype;                if (t) {                    while (t) {                        v = v.constructor.prototype;                        t -= 1;                    }                    f = v[name];                } else {                    // 個人覺得這段代碼有點繁瑣,既然uber的含義就是父類的函數,那麼f直接指向v[name]就可以了                    f = p[name];                    if (f == this[name]) {                        f = v[name];                    }                }                d[name] += 1;                // 執行父類中的函數name,但是函數中this指向當前對象                // 同時注意使用Array.prototype.slice.apply的方式對arguments進行截斷(因為arguments不是標準的數組,沒有slice方法)                r = f.apply(this, Array.prototype.slice.apply(arguments, [1]));                d[name] -= 1;                return r;            });            return this;        });        

注意,在inherits函數中還有一個小小的BUG,那就是沒有重定義constructor的指向,所以會發生如下的錯誤:

        var zhang = new Employee("ZhangSan", "1234");        console.log(zhang.getName());   // "Employee name: ZhangSan"        console.log(zhang.constructor === Employee);    // false        console.log(zhang.constructor === Person);      // true        

 

改進建議

根據前面的分析,個人覺得method函數必要性不大,反而容易混淆視線。 而inherits方法可以做一些瘦身(因為Crockford可能考慮更多的情況,原文中介紹了好幾種使用inherits的方式,而我們只關注其中的一種), 並修正了constructor的指向錯誤。

        Function.prototype.inherits = function(parent) {            this.prototype = new parent();            this.prototype.constructor = this;            this.prototype.uber = function(name) {                f = parent.prototype[name];                return f.apply(this, Array.prototype.slice.call(arguments, 1));            };        };        

調用方式:

        function Person(name) {            this.name = name;        }        Person.prototype.getName = function(prefix) {            return prefix + this.name;        };        function Employee(name, employeeID) {            this.name = name;            this.employeeID = employeeID;        }        Employee.inherits(Person);        Employee.prototype.getName = function() {            return this.uber("getName", "Employee name: ");        };        var zhang = new Employee("ZhangSan", "1234");        console.log(zhang.getName());   // "Employee name: ZhangSan"        console.log(zhang.constructor === Employee);   // true        

 

有點意思

在文章的結尾,Crockford居然放出了這樣的話:

I have been writing JavaScript for 8 years now, and I have never once found need to use an uber function. The super idea is fairly important in the classical pattern, but it appears to be unnecessary in the prototypal and functional patterns. I now see my early attempts to support the classical model in JavaScript as a mistake.

可見Crockford對在JavaScript中實現物件導向的編程不贊成,並且聲稱JavaScript應該按照原型和函數的模式(the prototypal and functional patterns)進行編程。 不過就我個人而言,在複雜的情境中如果有物件導向的機制會方便的多。 但誰有能擔保呢,即使像jQuery UI這樣的項目也沒用到繼承,而另一方面,像Extjs、Qooxdoo則極力倡導一種物件導向的JavaScript。 甚至Cappuccino項目還發明一種Objective-J語言來實踐物件導向的JavaScript。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.