JS面向对象方法继承

ES5 实现方法继承:

function Animal(type) {
    this.type = type;
}
Animal.prototype.eat = function() {
    console.log("动物都会吃饭");
}
var a = new Animal();

function Dog(type, name) {
    Animal.call(this, type);
    this.name = name;
}
// 创建一个Animal对象,Animal对象的原型__proto__指向Animal.prototype,所以子类的Dog的实例可以通过原型找到Animal的方法
Dog.prototype = new Animal();
// Dog的原型对象中的constructor属性指回Dog,保证Dog的对象是它自己创造的
Dog.prototype.constructor = Dog;

Dog.prototype.wang = function() {
    console.log("狗狗都会汪汪叫");
}

var dog = new Dog("dog", '大黄');


dog.eat();
dog.wang();

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
在原生 JavaScript 中,可以通过构造函数和原型链来实现面向对象继承。具体实现方式如下: 1. 构造函数继承 构造函数继承是通过在子类构造函数中调用父类构造函数来实现的。这种方式的缺点是无法继承父类原型上的方法和属性。 ```javascript function Parent(name) { this.name = name; } function Child(name, age) { Parent.call(this, name); this.age = age; } var child = new Child('Tom', 18); console.log(child.name); // Tom console.log(child.age); // 18 ``` 2. 原型链继承 原型链继承是通过将子类的原型指向父类的实例来实现的。这种方式的缺点是所有子类实例共享父类实例上的属性和方法。 ```javascript function Parent() { this.name = 'parent'; } Parent.prototype.sayHello = function() { console.log('Hello'); }; function Child() {} Child.prototype = new Parent(); var child1 = new Child(); var child2 = new Child(); console.log(child1.name); // parent console.log(child2.name); // parent child1.sayHello(); // Hello child2.sayHello(); // Hello ``` 3. 组合继承 组合继承是将构造函数继承和原型链继承结合起来使用的一种方式。这种方式既可以继承父类实例上的属性和方法,也可以继承父类原型上的属性和方法。 ```javascript function Parent(name) { this.name = name; } Parent.prototype.sayHello = function() { console.log('Hello'); }; function Child(name, age) { Parent.call(this, name); this.age = age; } Child.prototype = new Parent(); Child.prototype.constructor = Child; var child = new Child('Tom', 18); console.log(child.name); // Tom console.log(child.age); // 18 child.sayHello(); // Hello ```

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

kobe_OKOK_

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值