首页 > 编程语言 > 详细

Javascript继承1:子类的的原型对象----类式继承

时间:2018-10-02 18:25:49      阅读:124      评论:0      收藏:0      [点我收藏+]
//声明父类
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) //[‘看书‘,‘旅游‘]

设计模式中的经典笔录

Javascript继承1:子类的的原型对象----类式继承

原文:https://www.cnblogs.com/-walker/p/9737375.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!