js 继承父构造函数的属性和方法

  • ES6之前没有extends,可以通过构造函数 + 原型对象实现继承,叫组合继承
call()
  • 调用这个函数,并修改函数运行时this指向
fun.call(thisArg,aeg1,aeg2....)
  • thisArg 调用函数的this的指向对象
  • aeg1,aeg2 传递参数
  1. 调用函数
function fn(x,y){
  console.log(this);
  console.log(x + y);
}
var star = {
  name : "刘德华"
}
 fn.call(star,16,20);
  • this 指向star 对象 输出36
借用构造函数继承父类型属性
  • 核心:通过call()把父类型的this指向子类型的this
function Father(name,age){
  this.name = name;
  this.age = age;
}
function Son(name,age,fee){
  Father.call(this,name,age);
  this.fee = fee;
}
var son = new Son('郭麒麟',20,1000);
借用原型对象继承父类型方法
Father.prototype.monry = function(){}

Son.prototype = new Father();
//需要利用constructor 指回原来的原型对象 
Son.prototype .constructor =Son;
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,让我来回答你的问题。 在 JavaScript 中,我们可以使用以下方式来定义构造函数 `Animal` 和 `Cat`,实现继承关系: ```javascript // 定义一个 Animal 构造函数 function Animal(name) { this.name = name; } // 在 Animal 的原型上定义一个 sayHi 方法 Animal.prototype.sayHi = function() { console.log(`Hi, I'm ${this.name}`); }; // 定义一个 Cat 构造函数继承自 Animal function Cat(name, color) { // 调用 Animal 的构造函数继承属性 Animal.call(this, name); this.color = color; } // 使用 Object.create 方法,将 Cat 的原型链连接到 Animal 的原型链上 Cat.prototype = Object.create(Animal.prototype); // 重置 Cat.prototype.constructor,使其指向 Cat 自身的构造函数 Cat.prototype.constructor = Cat; // 在 Cat 的原型上定义一个 catchMouse 方法 Cat.prototype.catchMouse = function() { console.log(`${this.name} is catching a mouse!`); }; ``` 现在,我们可以实例化一个 `Animal` 和一个 `Cat`,并调用它们的方法: ```javascript const animal = new Animal('Animal'); const cat = new Cat('Tom', 'grey'); animal.sayHi(); // Hi, I'm Animal cat.sayHi(); // Hi, I'm Tom cat.catchMouse(); // Tom is catching a mouse! ``` 注意,在构造函数 `Cat` 中,我们使用了 `call` 方法调用了 `Animal` 的构造函数,以继承 `Animal` 的属性。在 `Cat.prototype` 中,我们使用了 `Object.create` 方法来将 `Animal.prototype` 所指向的原型链传递到 `Cat.prototype` 上,从而实现了继承关系。最后,我们重置了 `Cat.prototype.constructor`,使其指向 `Cat` 自身的构造函数,以便在调试时查看自身的构造函数

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值