本文實例總結了JavaScript類的繼承操作。分享給大家供大家參考,具體如下:
一、類式繼承
首先要做的是創建構造函數。按慣例,其名稱就是類名,首字母應該大寫。在構造函數中,創建實例屬性要用關鍵字this 。類的方法則被添加到prototype對象中。要創建該類的實例,只需結合關鍵字new調用這構造函數即可。
/* Class Person. */function Person(name) { this.name = name;}Person.prototype.getName = function() { return this.name;}var reader = new Person('John Smith');reader.getName();二、原型鏈
JavaScript的每個對象都有一個名為prototype的屬性,這個屬性要么指向另一個對象,要么是null.在訪問對象的某個成員時,如果這個成員未見于當前對象,那么就會到prototype所指的對象中去查找。如果還是沒有找到,那么就會沿著原型鏈逐一訪問每個原型對象,直到找到這個成員。這意味著讓一個類繼承另一個類,只需將子類的prototype設置為超類的一個實例即可。
為了讓Author繼承Person,必須手工將Author的prototype設置為Person的一個實例。最后一步是將prototype的construct屬性重設為Author(因為prototype屬性設置為Person的實例)時,其construct屬性被抹除了。
function Author(name, books) { Person.call(this, name); // Call the superclass' constructor in the scope of this. this.books = books; // Add an attribute to Author.}Author.prototype = new Person(); // Set up the prototype chain.Author.prototype.constructor = Author; // Set the constructor attribute to Author.Author.prototype.getBooks = function() { // Add a method to Author. return this.books;};var author = [];author[0] = new Author('Dustin Diaz', ['JavaScript Design Patterns']);author[1] = new Author('Ross Harmes', ['JavaScript Design Patterns']);console.log(author[1].getName());console.log(author[1].getBooks());三、extend函數
為了簡化類的聲明,可以把派生子類的整個過程包裝在一個名為extend的函數中。它的作用與其他語言的extend關鍵字類似,即基于一個給定的類的結構創建一個新的類:
function extend(subClass, superClass) { var F = function() {}; F.prototype = superClass.prototype; subClass.prototype = new F(); subClass.prototype.constructor = subClass;}其實所做的事與之前的是一樣的。它先設置了prototype,然后再將其constructor重設為恰當的值。并且中間利用了一個空函數,這樣就可以避免創建超類的實例。使用extend繼承的寫法:
function Person(name) { this.name = name;}Person.prototype.getName = function() { return this.name;}/* Class Author. */function Author(name, books) { Person.call(this, name); this.books = books;}extend(Author, Person);Author.prototype.getBooks = function() { return this.books;};
新聞熱點
疑難解答
圖片精選