JS中继承

1、原型链来实现继承

原型链实现继承的本质是重新原型对象,代之以一个新类型的实例。

function Test(city) {
  this.name = 'max';
  this.city = city;
  this.friends = ['egbert', 'helen', 'smith'];
}

Test.prototype.sayName = function() {
  console.log('hi, my name is ' + this.name + '!');
}

function InhertTest() {
  this.age = 24;
}

InhertTest.prototype = new Test();

var t = new InhertTest();

console.log(t.name);  // 打印出来的是max

在这里插入图片描述
原型链继承有两个问题,一个是无法向超类型的构造函数传递参数,另一个是所有的InhertTest都会共享一个friends实例。friends存放在InhertTest.prototype中,所有实例都会共享。

2、借用构造函数

在子类型构造函数的内部调用超类型构造函数。

function Test(city) {
  this.name = 'max';
  this.city = city;
  this.friends = ['egbert', 'helen', 'smith'];
}

Test.prototype.sayName = function() {
  console.log('hi, my name is ' + this.name + '!');
}

function InhertTest(city) {
  Test.call(this, city);
  this.age = 24;
}

var t = new InhertTest('beijing');

console.log(t.city);  // 打印出来的是beijing

PS: 为了保证超类型的属性不会覆盖子类型的属性,可以先调用超类型的构造函数。
这样写,name, city和friends都在InhertTest的实例上,也就是在t上。缺点就是子类型不能继承超类型在原型上的方法和属性。

PS:今天先写这两种吧,我要睡中觉了。。。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值