当前位置: 移动技术网 > IT编程>开发语言>JavaScript > Javascript继承2:创建即继承----构造函数继承

Javascript继承2:创建即继承----构造函数继承

2018年10月03日  | 移动技术网IT编程  | 我要评论
//声明父类
function superclass(id){
    //值类型公有属性
    this.id = id;
    //引用类型公有属性
    this.books = ['html','css'];
}
//父类声明原型方法
superclass.prototype.showbooks = function(){
    console.log(this.books)
}
//声明子类
function childclass(id){
    //继承父类
    superclass.call(this,id)
}

var child1 = new childclass(1)
var child2 = new childclass(2)
child1.books.push('设计模式');
console.log(child1.id)    //1
console.log(child1.books) //['html','css','设计模式'];
console.log(child2.id)    //2
console.log(child2.books) //['html','css'];

child1.showbooks()          //typeerrr
/*
* superclass.call(this,id)是构造函数继承的精华,call可以改变函数的作用域环境,
* 因此在子类中对父类调用这个方法,就是将子类的变量在父类中执行一遍,由于父类中是给
* this绑定属性的,因此子类也就继承了父类的公有属性,由于这种方法没有涉及原型prototype
* 所以父类原型方法不会被子类继承,如果想要被继承就必须放在构造函数中,这样创建出来
* 的每个实例都会单独拥有一份而不能共用,这样就违背了代码服用的原则。
* 为了综合这两种模式的优点,有了组合式继承。
*/

 设计模式中的经典笔录

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网