JavaScript继承

JavaScript中的继承

构造函数继承(修改 this 指向)

缺点: 每实例一次就开辟一次空间,影响性能。

function Person(name, age) {
  this.name = name;
  this.age = age;
  this.showName = function () {
    return this.name;
  };
}
//改变this指向
function Student(name, age) {
  Person.call(this, name, age);
  // Person.apply(this,arguments)
  // Person.bind(this,name,age)()
}
let xm = new Student("小明", 18);
console.log(xm.showName()); //小明

原型链继承

缺点: 不能实现多继承;每一个对象都共享一个属性。

function Person() {}
Person.prototype.name = "小明";
Person.prototype.age = 18;
Person.prototype.showName = function () {
  return this.name;
};
// let xm = new Person();
// console.log(xm.showName());
// 原型链
function Student() {}
Student.prototype = new Person();
let xm = new Student();
console.log(xm);

混合原型链继承

缺点: 生成俩份实例。

function Person(name, age) {
  // 实例属性
  this.name = name;
  this.age = age;
}
// 原型方法
Person.prototype.showName = function () {
  return this.name;
};
function Student(name, age) {
  Person.apply(this, arguments);
  // Person.bind(this,name,age)()
}
Student.prototype = new Person();
let xm = new Student("小明", 18);
console.log(xm.showName()); //小明

混合寄生继承

function Person(name, age) {
  // 实例属性
  this.name = name;
  this.age = age;
}
// 原型方法
Person.prototype.showName = function () {
  return this.name;
};
function Student(name, age) {
  Person.apply(this, arguments);
}
for (key in Person.prototype) {
  Student.prototype[key] = Person.prototype[key];
}
let xm = new Student("小明", 18);
console.log(xm.showName()); //小明
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值