function Teacher(){
this.student = 500; // 原始值
this.skill = ["JS", "JQ"]; // 引用值
}
var teacher = new Teacher();
Student.prototype = teacher;
function Student(){}
var student = new Student();
student.student ++;
student.skill.push("HTML", "CSS");
- 实例是修改自身的属性,并不能修改原型上的属性
- 如果说当前的修改是原型上的引用值,并没有修改引用,所以可以修改
function Parent(){
this.a = 1;
this.b = [1, 2, this.a]; // 因为this.a是原始值,相当于[1, 2, 1]
this.c = {
demo: 5
};
this.show = function(){
console.log(this.a, this.b, this.c.demo);
}
}
function Child(){
this.a = 2;
this.change = function(){
this.b.push(this.a);
this.a = this.b.length;
this.c.demo = this.a++; //相当于 this.c.demo = this.a; this.a = this.a + 1;
}
}
Child.prototype = new Parent(); // 因为这里是new出来的实例,不会影响parent, child1 / child2 是同一引用相互影响
var parent = new Parent();
var child1 = new Child();
var child2 = new Child();
child1.a = 11;
child2.a = 12;
parent.show(); // 1 [1, 2, 1] 5
child1.show(); // 11 [1, 2, 1] 5
child2.show(); // 12 [1, 2, 1] 5
child1.change(); // __proto__.b:[1,2,1, a->11]; a:4; __proto__.c.demo:4; a:5; ==> a:5, __proto__.b:[1, 2, 1, 11], __proto__.c:{demo:4}
child2.change(); // __proto__.b:[1,2,1,11, a->12]; a:5; __proto__.c.demo:4; a:6; ==> a:6, __proto__.b:[1, 2, 1, 11, 12], __proto__.c:{demo:5}
parent.show(); // 1 [1, 2, 1] 5
child1.show(); // 5 [1, 2, 1, 11, 12] 5
child2.show(); // 6 [1, 2, 1, 11, 12] 5