今天开始学习面向对象编程的核心概念——继承与多态,发现这两个概念和现实生活的现象很像,学起来挺有意思的。
先试着写了一个父类Animal和子类Dog的例子,发现继承真的像"遗传"一样:
..Animal(...)
继承父类的功能// 定义父类Animal
class Animal {
ctor(name) {
this.name = name;
}
speak = function() {
return this.name + " makes a sound.";
}
}
// Dog类继承Animal
class Dog {
ctor(...) {
this = ..Animal(...); // 调用父类构造函数
}
// 重写speak方法
speak = function() {
return this.name + " barks.";
}
}
import console;
var myDog = Dog("Buddy");
console.log(myDog.speak()); // 输出:Buddy barks.
console.pause();
又试了三层继承(Animal→Dog→Puppy),发现子类可以层层继承上层的所有功能:
import console;
class Animal {
ctor(name) {
this.name = name;
}
speak = function() {
return this.name + " makes a sound.";
}
}
class Dog {
ctor(...) {
this = ..Animal(...);
}
speak = function() {
return this.name + " barks.";
}
}
class Puppy {
ctor(...) {
this = ..Dog(...);
}
speak = function() {
return this.name + " puppy barks softly.";
}
}
var myPuppy = Puppy("Tommy");
console.log(myPuppy.speak()); // 输出:Tommy puppy barks softly.
console.pause();
写一个猫狗的例子理解多态,发现它的核心是"同一个方法名,不同对象有不同表现":
class Animal {
ctor(name) {
this.name = name;
}
speak = function() {
return this.name + " makes a sound.";
}
}
class Dog {
ctor(...) {
this = ..Animal(...);
}
speak = function() {
return this.name + " barks.";
}
}
class Cat {
ctor(...) {
this = ..Animal(...);
}
speak = function() {
return this.name + " meows.";
}
}
function makeSound(animal) {
console.log(animal.speak());
}
import console;
var myDog = Dog("Buddy");
var myCat = Cat("Whiskers");
makeSound(myDog); // 输出:Buddy barks.
makeSound(myCat); // 输出:Whiskers meows.
console.pause();
把不同动物对象放到数组里统一处理,更能体现多态的便利:
class Animal {
ctor(name) {
this.name = name;
}
speak = function() {
return this.name + " makes a sound.";
}
}
class Dog {
ctor(...) {
this = ..Animal(...);
}
speak = function() {
return this.name + " barks.";
}
}
class Cat {
ctor(...) {
this = ..Animal(...);
}
speak = function() {
return this.name + " meows.";
}
}
import console;
var animals = {Dog("Buddy"), Cat("Whiskers")};
for(k, animal in animals) {
console.log(animal.speak());
}
// 输出:
// Buddy barks.
// Whiskers meows.
console.pause();
import math;
import console;
class Shape {
area = function() { return 0; } // 父类默认返回0
}
class Circle {
ctor(radius, ...) {
this = ..Shape(...);
this.radius = radius;
}
area = function() {
return ..math.pi * this.radius * this.radius;
}
}
class Rectangle {
ctor(width, height, ...) {
this = ..Shape(...);
this.width = width;
this.height = height;
}
area = function() {
return this.width * this.height;
}
}
var shapes = {Circle(5), Rectangle(4, 6)};
for(k, shape in shapes) {
console.log("面积: " + shape.area());
}
// 输出:
// 面积: 78.539816339745
// 面积: 24
console.pause();
..父类名(...)
实现构造继承,避免重复代码。原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。