Javascript繼承1:子類的的原型對象----類式繼承

//聲明父類
function Parent(){
    this.parentValue = true;
    this.favorites = ['看書']
}
//爲父類添加公有方法
Parent.prototype.getParentValue = function(){
    return this.parentValue;
}
//聲明子類
function Child(){
    this.childValue = false;
}
// 繼承父類
Child.prototype =  new Parent()
//爲子類添加方法
Child.prototype.getChildValue = function(){
    return this.childValue;
}

var instance = new Child()
console.log(instance.getParentValue())  //true
console.log(instance.getChildValue())   //false
/*
*注:使用instanceof檢測某個對象是不是某個某個類的實例,
*    或者說某個對象是否繼承了某個類
*/
console.log(instance instanceof Parent) //true
console.log(instance instanceof Child)  //true
console.log(Child instanceof Parent)    //false 爲什麼?Child的原型繼承了父類

console.log(Child.prototype instanceof Parent) //true
/*
*缺點:一個子類改變繼承於父類的公有屬性,其餘子類會受到影響
*    如何避免??下一小節
*/
var child1 = new Parent()
var child2 = new Parent()
console.log(child2.favorites) //['看書']
child1.favorites.push('旅遊')
console.lof(child2.favorites) //['看書','旅遊']

設計模式中的經典筆錄設計模式

相關文章
相關標籤/搜索