JavaScript继承总结笔记

//原型链
//借用构造函数模式
//组合模式
//原型式继承

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();

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值