javaScript面向物件程式設計-繼承(二)
阿新 • • 發佈:2018-12-10
原型繼承
原型繼承是對類式繼承的一種封裝,其中的過渡物件就相當於類式繼承中的子類,只是在原型式中作為一個過渡物件出現,目的是建立要返回的新的例項化物件。和類式繼承一樣,父類物件book中指型別的屬性被複制,引用型別的屬性被共有。
//原型是繼承 function inheritObject(o) { //宣告一個過渡函式物件 function F(){} //過渡物件的原型繼承父類 F.prototype = o; //返回過渡物件的一個例項,該例項的原型繼承了父物件 return new F(); } var book ={ name:"js", alikeBook:["css","html"] }; //測試程式碼 var newBook = inheritObject(book); newBook.name ="ajax"; newBook.alikeBook.push("new xml book"); var otherBook = inheritObject(book); otherBook.name ="flash"; otherBook.alikeBook.push("other as book"); console.log(newBook.name);//ajax console.log(newBook.alikeBook);//[ 'css', 'html', 'new xml book', 'other as book' ] console.log(otherBook.name);//flash console.log(otherBook.alikeBook);//[ 'css', 'html', 'new xml book', 'other as book' ] console.log(book.name);//js console.log(book.alikeBook);//[ 'css', 'html', 'new xml book', 'other as book' ]
寄生式繼承
寄生式繼承是對原型繼承的第二次封裝,並且在封裝的過程中對繼承物件進行了擴充套件,這樣新建立的物件不僅僅有父類中的屬性和方法,而且添加了新的屬性和方法。
//寄生式繼承var newBook = createBook(book);newBook.name = "js";newBook.alikeBook.push("new");var otherBook = createBook(book);otherBook.name = "bad";otherBook.alikeBook.push("other"); //宣告基物件 var book = { name:'js book', alikeBook: ["css","html"] }; function createBook(obj) { //通過原型繼承方式建立新物件 var o = new inheritObject(obj); o.getName = function () { console.log(name); } //返回拓展後的新物件 return o; } //測試程式碼 var newBook = createBook(book); newBook.name = "js"; newBook.alikeBook.push("new"); var otherBook = createBook(book); otherBook.name = "bad"; otherBook.alikeBook.push("other"); console.log(newBook.name);//ajax console.log(newBook.alikeBook);//[ 'css', 'html', 'new xml book', 'other as book' ] console.log(otherBook.name);//flash console.log(otherBook.alikeBook);//[ 'css', 'html', 'new xml book', 'other as book' ] console.log(book.name);//js console.log(book.alikeBook);//[ 'css', 'html', 'new xml book', 'other as book' ]