//原型链
//借用构造函数模式
//组合模式
//原型式继承
function SubType() {
this.language = 'JavaScript';
}
function SuperType() {
this.welldone = 'DataBase';
this.projects = ['operation', 'algorithm'];
}
Object.defineProperties(SuperType.prototype, {
'hobby': {
configurable: true,
enumerable: true,
writable: false,
value: 'thinking'
}
});
SubType.prototype = new SuperType();
let sub1 = new SubType();
let sub2 = new SubType();
sub1.language = 'C++';
sub2.language = 'C#';
console.log('===========');
console.log(sub1.language);
console.log(sub2.language);
console.log('===========');
console.log(sub1.welldone);
sub1.welldone = 'NetWork';
console.log(sub1.welldone);
console.log(sub2.welldone);
console.log('===========');
console.log(sub1.projects);
sub1.projects.push(['编译原理', '代码大全']);
console.log(sub1.projects);
console.log(sub2.projects);
console.log('===========');
console.log(sub1.hobby);
sub1.hobby = 'reading';
console.log(sub1.hobby);
console.log(sub2.hobby);
/*
理解原型链机制实现的继承
SubType继承SuperType,要达到的目的是
SuperType构造函数中的属性被SubType构造函数所继承,每一个SubType都有一份自己的属性。
SuperType原型对象中的方法和属性对SubType实例而言是共享的。
有一个问题需要阐释:那就是SubType的实例对象sub1和sub2的共同的原型都是SuperType的某个实例super,
那么就存在一个问题,super中势必存在welldone和projects,那么welldone和projects应该是共享的,
这就是一对矛盾:也即是说既要求SuperType构造函数中的属性为SubType实例私有,又要求为SubType实例所共享。
解决这个矛盾的途径就是借用构造函数,原理就是显示绑定this的指向。另外就是子类型中存在的属性会屏蔽夫类型中的同名属性。
将子类型实例共享的一些方法和属性可以定义在父类型的原型对象中。
*/
function SubType() {
SuperType.call(this);
this.language = 'JavaScript';
}
function SuperType() {
this.welldone = 'DataBase';
this.projects = ['operation', 'algorithm'];
}
SuperType.prototype.test = function() {
console.log('this a test');
}
Object.defineProperties(SuperType.prototype, {
'hobby': {
configurable: true,
enumerable: true,
writable: false,
value: 'thinking'
}
});
SubType.prototype = new SuperType();
let sub1 = new SubType();
let sub2 = new SubType();
console.log(sub1.language);
sub1.language = 'GoLang';
console.log(sub2.language);
console.log(sub1.welldone);
sub1.welldone = 'C++';
console.log(sub2.welldone);
console.log(sub1.projects);
sub1.projects.push('tree');
console.log(sub1.projects);
console.log(sub2.projects);
sub1.test();
sub2.test();
![](https://i-blog.csdnimg.cn/blog_migrate/d8d1de1d16502a60e3c5ed369158ee36.jpeg)