原型继承
原型继承是对类式继承的一种封装,其中的过渡对象就相当于类式继承中的子类,只是在原型式中作为一个过渡对象出现,目的是创建要返回的新的实例化对象。和类式继承一样,父类对象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);//ajaxconsole.log(newBook.alikeBook);//[ 'css', 'html', 'new xml book', 'other as book' ]console.log(otherBook.name);//flashconsole.log(otherBook.alikeBook);//[ 'css', 'html', 'new xml book', 'other as book' ]console.log(book.name);//jsconsole.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);//ajaxconsole.log(newBook.alikeBook);//[ 'css', 'html', 'new xml book', 'other as book' ]console.log(otherBook.name);//flashconsole.log(otherBook.alikeBook);//[ 'css', 'html', 'new xml book', 'other as book' ]console.log(book.name);//jsconsole.log(book.alikeBook);//[ 'css', 'html', 'new xml book', 'other as book' ]