如何在JavaScript中创建抽象基类? [英] How do I create an abstract base class in JavaScript?

查看:217
本文介绍了如何在JavaScript中创建抽象基类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在JavaScript中模拟抽象基类?最优雅的方式是什么?

Is it possible to simulate abstract base class in JavaScript? What is the most elegant way to do it?

说,我想做类似的事情: -

Say, I want to do something like: -

var cat = new Animal('cat');
var dog = new Animal('dog');

cat.say();
dog.say();

它应输出:'bark','meow'

It should output: 'bark', 'meow'

推荐答案

创建抽象类的一种简单方法是:

One simple way to create an abstract class is this:

/**
 @constructor
 @abstract
 */
var Animal = function() {
    if (this.constructor === Animal) {
      throw new Error("Can't instantiate abstract class!");
    }
    // Animal initialization...
};

/**
 @abstract
 */
Animal.prototype.say = function() {
    throw new Error("Abstract method!");
}

Animal class和方法是抽象的。

The Animal "class" and the say method are abstract.

创建实例会引发错误:

new Animal(); // throws

这就是你继承它的方式:

This is how you "inherit" from it:

var Cat = function() {
    Animal.apply(this, arguments);
    // Cat initialization...
};
Cat.prototype = Object.create(Animal.prototype);
Cat.prototype.constructor = Cat;

Cat.prototype.say = function() {
    console.log('meow');
}

看起来只是喜欢它。

这就是你的情景的表现:

And this is how your scenario plays out:

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

cat.say();
dog.say();

小提琴这里(查看控制台输出)。

Fiddle here (look at the console output).

这篇关于如何在JavaScript中创建抽象基类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆