代碼詳解:使用JavaScript進(jìn)行面向?qū)ο缶幊痰闹改?/h1>
一切都從對(duì)象開始。
對(duì)象,即我們相互交流的一個(gè)載體,有其屬性和方法。對(duì)象是面向?qū)ο缶幊痰暮诵?,不僅用于JavaScript,而且還適用于Java、C語言、C++等。不再考慮單個(gè)變量和函數(shù),而選擇自給型的對(duì)象。
以下是在討論面向?qū)ο缶幊?OOP)時(shí)最常用到的概念:
- 對(duì)象,屬性,方法
- 類
- 封裝
- 抽象
- 復(fù)用/繼承
- 多態(tài)性
- 關(guān)聯(lián)
- 聚合
- 組合
1. 對(duì)象,屬性,方法
1.1 對(duì)象字面量(Objectliteral)
在大括號(hào)中設(shè)置屬性,從而在JavaScript中創(chuàng)建一個(gè)新對(duì)象。對(duì)象字面量屬性值可以是任何數(shù)據(jù)類型,如函數(shù)字面量、數(shù)組、字符串、數(shù)字或布爾值。
下面創(chuàng)建一個(gè)命名圖書的對(duì)象,其屬性包括作者、出版年份、標(biāo)題和方法。
- — summary.
- constbook = {
- title: "Hippie",
- author: "Paulo Coelho",
- year: "2018"
- }
對(duì)象創(chuàng)建完成后,可以使用點(diǎn)記法獲取值。例如,可以使用book.title.獲取標(biāo)題的值,還可以使用方括號(hào)book[‘title’]訪問屬性。
1.2 對(duì)象構(gòu)造函數(shù)(Objectconstructor)
對(duì)象構(gòu)造函數(shù)與常規(guī)函數(shù)相同。每次創(chuàng)建對(duì)象時(shí)都會(huì)用到??蓪⑵渑c新關(guān)鍵字一起使用。當(dāng)需要?jiǎng)?chuàng)建具有相同屬性和方法的多個(gè)對(duì)象時(shí),對(duì)象構(gòu)造函數(shù)非常有用。
- constbook = {
- title: "Hippie",
- author: "Paulo Coelho",
- year: "2018"
- }const book1 = {
- title: "The Alchemist",
- author: "Paulo Coelho",
- year: "1988",
- }
如果要?jiǎng)?chuàng)建多個(gè)書籍(book)對(duì)象,必須為每本書復(fù)制代碼??梢岳^續(xù)創(chuàng)建 book對(duì)象,但這有點(diǎn)麻煩——不過對(duì)象構(gòu)造函數(shù)有助于再次使用對(duì)象字面量。
- functionBook(title, author, year) {
- this.title = title;
- this.author = author;
- this.year = year;
- }const book1 = new Book ('Hippie', 'Paulo Coelho',
- '2018');
- console.log(book1);
- > Book {
- title: "Hippie",
- author: "Paulo Coelho",
- year: "2018"
- }// if we want to create more than onebook just we call
- function book with new keyword.const book2
- = new Book ('TheAlchemist', 'Paulo Coelho', '1988');
book1 和 book2創(chuàng)建 Book的實(shí)例并將其分配給變量。想知道一個(gè)對(duì)象是否是另一個(gè)對(duì)象的實(shí)例??梢杂胕nstanceof。
- book1 instanceof Book
- > true
1.3 Object.create()方法
JavaScript中的每個(gè)對(duì)象都將從主對(duì)象創(chuàng)建。任何時(shí)候使用大寫字母“O”時(shí),指的都是主對(duì)象。我們可以在console控制臺(tái)中打印主對(duì)象。主對(duì)象有很多方法,下面來看object.create()方法。
Object.create()創(chuàng)建法使用現(xiàn)有對(duì)象作為原型來創(chuàng)建新對(duì)象。基本語法如下:
- Object.create(proto,[propertiesObject])
proto是新建對(duì)象的原型。 propertiesObject是一個(gè)可選項(xiàng)。
下面舉個(gè)簡(jiǎn)單的例子:
- constBook = {
- summary : function() {
- console.log(`${this.title} iswritten by ${this.author}.`)
- }
- }const book1 = Object.create(Book);
- book1.author = "Paulo Coelho";
- book1.title = "Hippie";console.log(book1.summary());
- > Hippie is written by Paulo Coelho.
以上的例子創(chuàng)建了一個(gè)原始對(duì)象book1,并為作者和標(biāo)題賦值。可以看到原始對(duì)象中的匯總函數(shù):
下面將Object.create() 方法進(jìn)行詳細(xì)介紹。
2. 類
類不是對(duì)象,它是對(duì)象的藍(lán)本,是特殊函數(shù)??梢允褂煤瘮?shù)的表達(dá)式和聲明來定義函數(shù),也可以這樣定義類。藍(lán)本可用來表示對(duì)象的數(shù)量。
可以使用類的關(guān)鍵字和名稱。語法與Java相似。
類語法是使用面向?qū)ο缶幊毯凸芾碓偷囊粋€(gè)好途徑:
- let Book= function(name) {
- this.name = name
- }let newBook = function(name) {
- Book.call(this, name)
- } newBook.prototype = Object.create(Book.prototype);
- const book1 = new newBook("The Alchemist");
此例使用了ES6類語法:
- classBook {
- constructor(name) {
- this.name = name
- }
- }class newBook extends Book {
- constructor(name) {
- super(name);
- }
- }const book1 = new newBook("The Alchemist");
類語法是語法糖(syntactical sugar)—而場(chǎng)景背后它仍然使用基于原型的模型。類是函數(shù),而函數(shù)是JavaScript中的對(duì)象。
- classBook {
- constructor(title, author){
- this.title = title;
- this.author = author;
- }
- summary() {
- console.log(`${this.title} writtenby ${this.author}`);
- }
- }const book1 = new Book("", "");
- console.log(typeof Book);
- > "function"console.log(typeof book1);
- > "object"
3. 封裝(Encapsulation)
封裝意為隱藏信息或數(shù)據(jù)。指對(duì)象在不向外部使用者透露任何執(zhí)行細(xì)節(jié)的情況下執(zhí)行其功能。換句話說,就是其私有變量只對(duì)當(dāng)前函數(shù)可見,而對(duì)全局范圍或其他函數(shù)不可訪問。
- constBook = function(t, a) {
- let title = t;
- let author = a;
- return {
- summary : function() {
- console.log(`${title} written by${author}.`);
- }
- }
- }
- const book1 = new Book('Hippie', 'Paulo Coelho');
- book1.summary();
- > Hippie written by Paulo Coelho.
在上面的代碼中,標(biāo)題和作者只在函數(shù)Book 的范圍內(nèi)可見,方法summary對(duì)Book的使用者可見。所以書名和作者被封裝在Book中。
4. 抽象
抽象意為實(shí)現(xiàn)隱藏。它是一種隱藏實(shí)現(xiàn)細(xì)節(jié)的方法,只向使用者顯示基本特性。換句話說,它隱藏了不相關(guān)的細(xì)節(jié),只顯示了必須對(duì)外部世界顯示的。缺乏抽象會(huì)導(dǎo)致代碼出現(xiàn)可維護(hù)性問題。
- constBook = function(getTitle, getAuthor) {
- // Private variables / properties
- let title = getTitle;
- let author = getAuthor;// Publicmethod
- this.giveTitle = function() {
- return title;
- }
- // Private method
- const summary = function() {
- return `${title} written by${author}.`
- }// Public method that has access toprivate method.
- this.giveSummary = function() {
- return summary()
- }
- }const book1 = new Book('Hippie', 'Paulo Coelho');
- book1.giveTitle();
- > "Hippie"book1.summary();
- > Uncaught TypeError: book1.summary is not a
- functionbook1.giveSummary();
- > "Hippie written by Paulo Coelho."
5. 復(fù)用/繼承
JavaScript繼承是一種機(jī)制,允許我們使用現(xiàn)有的類創(chuàng)建一個(gè)新類。也就是子類繼承父類的所有屬性和行為。
一般來說,JavaScript不是一種基于類的語言。關(guān)鍵字“類”是在ES6中引入的,但它是語法糖,JavaScript仍然是基于原型的。在JavaScript中,繼承是通過使用原型來實(shí)現(xiàn)的。這種模式稱為行為委托模式或原型繼承。
同樣可以通過book例子來體現(xiàn):
- functionBook(title, author, year) {
- this.title = title;
- this.author = author;
- this.year = year;
- this.summary = function() {
- console.log(`${this.title} iswritten by ${this.author}.`)
- }
- }
- const book1 = new Book ('Hippie', 'Paulo Coelho', '2018');
- const book2 = newBook ('The Alchemist', 'Paulo Coelho',
- '1988');
原型繼承
對(duì)于Book的每個(gè)實(shí)例,我們都在為基類中的方法重建內(nèi)存。這些方法必須在所有實(shí)例之間共享 — 不應(yīng)特定于個(gè)別實(shí)例中。圖中的原型是:
- letCorebook = function(title) {
- this.title = title
- }Corebook.prototype.title = function() {
- console.log(`name of the book is${this.title}`);
- }Corebook.prototype.summary = function(author) {
- console.log(`${this.title} is writtenby ${this.author}`);
- }let Book = function(title, author) {
- Corebook.call(this, title, author)
- }Book.prototype = Object.create(Corebook.prototype);
- let book1
- = new Book('TheAlchemist', 'Paulo Coelho');book1.title();
- > name of the book is The Alchemistbook1.summary();
- > The Alchemist is written by Paulo Coelho
在上面的代碼中,Book 的實(shí)例有一個(gè)原型的副本,能夠鏈接到Book的原型,而Book的原型又鏈接到Corebook的原型。
6. 多態(tài)
在不同的對(duì)象上使用同一方法,并讓每個(gè)對(duì)象具有自己的表現(xiàn)形式或形態(tài)的能力,稱為多態(tài)。
- letbook1 = function () {}
- book1.prototype.summary = function() {
- return "summary of book1"
- }let book2 = function() {}
- book2.prototype = Object.create(book1.prototype);
- book2.prototype.summary = function() {
- return "summary of book2"
- }let book3 = function() {}
- book3.prototype = Object.create(book1.prototype);
- book3.prototype.summary = function() {
- return "summary of book3"
- }
- var books = [new book1(), new book2(), new book3()];
- books.forEach(function(book){
- console.log(book.summary());
- });> summary of book1
- > summary of book2
- > summary of book3
對(duì)象之間的關(guān)系將由關(guān)聯(lián)、聚合和組合定義。
7. 關(guān)聯(lián)
關(guān)聯(lián)是兩個(gè)或多個(gè)對(duì)象之間的關(guān)系。每個(gè)對(duì)象都是獨(dú)立的。換句話說,關(guān)聯(lián)定義了對(duì)象之間的多重性:一對(duì)一、一對(duì)多、多對(duì)一、多對(duì)多。
- functionBook(title, author) {
- this.title = title;
- this.author = author;
- }
- const book1 = new Book ('Hippie', 'Paulo Coelho');
- const book2 = new Book ('TheAlchemist',
- 'Paulo Coelho');
- book2.multiplicity
- = book1
book1 賦值于book2的屬性多樣化,顯示對(duì)象book1 和 book2之間的關(guān)系。兩者都可以獨(dú)立添加和刪除。
8. 聚合
聚合是關(guān)聯(lián)的特例。在兩個(gè)對(duì)象之間的關(guān)系中,一個(gè)對(duì)象可能比另一個(gè)更重要。換句話說,當(dāng)一個(gè)對(duì)象比另一個(gè)擁有更多的所有權(quán)時(shí),這就是聚合。對(duì)象所有者通常稱為聚合,被所有者稱為組件。聚合又叫“Has-a”關(guān)系。
- functionBook(title, author) {
- this.title = title;
- this.author = author;
- }
- const book1 = new Book ('Hippie', 'Paulo Coelho');
- const book2 = new Book ('TheAlchemist', 'Paulo Coelho');
- let publication = {
- "name": "new publicationInc",
- "books": []
- }publication.books.push(book1);
- publication.books.push(book2);
book1 和 book2 被添加到對(duì)象publication下設(shè)的books中。如果在book1和book2 運(yùn)行之后刪除publication,則 Book和 publication 都將獨(dú)立運(yùn)行。
9. 組合
組合是聚合的一種特殊情況。一個(gè)對(duì)象包含另一個(gè)對(duì)象,并且被包含的對(duì)象脫離后無法生存。
- let Book= {
- "title": "TheAlchemist",
- "author": "PauloCoelho",
- "publication": {
- "name": "newpublication Inc",
- "address":"chennai"
- }
- }
這里屬性publication與 Book 對(duì)象有嚴(yán)格的限制,publication不能沒有Book對(duì)象。如果Book的id被刪除,則publication也將被刪除。
重組合輕繼承
繼承指一個(gè)對(duì)象基于另一個(gè)對(duì)象的情況。例如,book1繼承了標(biāo)題、作者和結(jié)語等書籍的屬性和方法,所以它建立了book1 is-a Book關(guān)系。
組合是收集單一對(duì)象并將它們組合起來構(gòu)建更復(fù)雜的對(duì)象。為構(gòu)建book1,需要一些方法,比如紙和筆。因此book1 has-a paper and a pen關(guān)系隨之出現(xiàn)。
- constgetTitle = (data) => ({
- title : () => console.log(`title :${data.title}`)
- });const getAuthor = (data) => ({
- author : () => console.log(`author:${data.author}`)
- });const getSummary = () => ({
- summary :() => console.log(`booksummary need to
- update.`)
- });const Book = (title, author) => {
- const data = {
- title,
- author
- }
- return Object.assign({},
- getTitle(data),
- getAuthor(data),
- getSummary()
- )
- }let book1 = Book('The Alchemist', 'Paulo Coelho');
- book1.title();
- > "title : The Alchemist"