// 定义一个父类Parent
function Parent() {
// 设置该类的属性a、b、c,方法show
// 数值型a
this.a = 1;
// 数组型b
this.b = [1, 2, this.a];
// 对象型c
this.c = {
demo: 5
};
// 函数型show,输出该类有意义的内容
this.show = function() {
console.log(this.a, this.b, this.c.demo);
}
}
// 定义一个类Child
function Child() {
// 定义该类的属性a
// 覆盖父类的属性a
this.a = 2;
// change函数,用于改变父类的属性值
this.change = function() {
// 改变父类的b属性值,添加当前a=2这个值
this.b.push(this.a);
// 再次改变a为父类数组b的长度
this.a = this.b.length;
// 改变父类c的demo值为b的长度
// 累加在后,使用累加之前的值
this.c.demo = this.a++;
}
}
// 继承父类Parent
Child.prototype = new Parent();
// 初始化一个Parent类的对象parent
var parent = new Parent();
// 初始化2个Child类的对象
var child1 = new Child();
var child2 = new Child();
// 设置它们各自的属性
child1.a = 11;
child2.a = 12;
// 打印parent的属性信息
parent.show();
// 子类调用父类方法show
child1.show();
child2.show();
// 子类调用自身方法change
child1.change();
child2.change();
// 再次显示,看看到底有何变化
parent.show();
child1.show();
child2.show();
// 打印parent的属性信息
// parent.show();
// 单纯的设置,没有问题
1 [1, 2, 1] 5
// child1.a = 11;
// child1.show();
11 [1, 2, 1] 5
// child2.a = 12;
// child2.show();
12 [1, 2, 1] 5
// parent.show();
1 [1, 2, 1] 5
// child1.change();
// child2.change();
// 5就是数组b的长度
5 [1, 2, 1, 11, 12] 5
// 在child1的基础上继续添加
// this.a累加之后变成6,其他不变
6 [1, 2, 1, 11, 12] 5