JS继承和多态

在JavaScript中,继承和多态是面向对象编程(OOP)的核心概念。

继承(Inheritance)

继承允许我们创建一个基于另一个类的新类,新类继承或扩展了原有类的属性和方法。在JavaScript中,继承通常通过原型链(Prototype Chain)实现。

1. 原型链继承

这是最简单的继承方式,通过设置构造函数的prototype属性来实现。

function Parent() {
  this.parentProperty = true;
}

Parent.prototype.getParentProperty = function() {
  return this.parentProperty;
};

function Child() {
  this.childProperty = false;
}

// 继承Parent
Child.prototype = new Parent();

// 新增或覆盖方法
Child.prototype.getChildProperty = function() {
  return this.childProperty;
};

var childInstance = new Child();
console.log(childInstance.getParentProperty()); // 输出 true
console.log(childInstance.getChildProperty()); // 输出 false
2. 构造函数继承

通过在子类构造函数中调用父类构造函数来实现。

function Parent(name) {
  this.name = name;
  this.colors = ['red', 'blue', 'green'];
}

function Child(name) {
  Parent.call(this, name); // 调用Parent构造函数并绑定this
}

var child1 = new Child('child1');
child1.colors.push('yellow');
console.log(child1.name); // 输出 'child1'
console.log(child1.colors); // 输出 ['red', 'blue', 'green', 'yellow']

var child2 = new Child('child2');
console.log(child2.name); // 输出 'child2'
console.log(child2.colors); // 输出 ['red', 'blue', 'green'],不受child1影响
3. 组合继承(原型链 + 构造函数)

结合了原型链和构造函数的优点。

function Parent(name) {
  this.name = name;
  this.colors = ['red', 'blue', 'green'];
}

Parent.prototype.sayName = function() {
  console.log(this.name);
};

function Child(name, age) {
  Parent.call(this, name); // 构造函数继承
  this.age = age;
}

Child.prototype = new Parent(); // 原型链继承
Child.prototype.constructor = Child;
Child.prototype.sayAge = function() {
  console.log(this.age);
};

var child = new Child('child', 18);
child.sayName(); // 输出 'child'
child.sayAge(); // 输出 18

多态(Polymorphism)

多态指的是同一个行为具有多个不同表现形式或形态的能力。在JavaScript中,多态通常通过继承和重写方法来实现。

function Animal() {}

Animal.prototype.speak = function() {
  console.log('Some sound');
};

function Dog() {}

Dog.prototype = new Animal();
Dog.prototype.speak = function() {
  console.log('Woof!');
};

function Cat() {}

Cat.prototype = new Animal();
Cat.prototype.speak = function() {
  console.log('Meow!');
};

// 多态性的体现
function makeSound(animal) {
  animal.speak();
}

var dog = new Dog();
var cat = new Cat();

makeSound(dog); // 输出 'Woof!'
makeSound(cat); // 输出 'Meow!'

在这个例子中,makeSound函数接受一个Animal类型的对象,并调用它的speak方法。由于DogCat都继承自Animal,并且它们都重写了speak方法,所以当传入不同的对象时,makeSound函数会表现出不同的行为,这就是多态的体现。

通过继承和多态,JavaScript允许我们创建可重用和可扩展的代码,这也是面向对象编程的核心优势之一

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值