如何在 JavaScript 中创建抽象基类? [英] How do I create an abstract base class in JavaScript?
本文介绍了如何在 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
类"和say
方法是抽象的.
创建实例会抛出错误:
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');
}
Dog
看起来很像.
这就是你的场景如何进行:
And this is how your scenario plays out:
var cat = new Cat();
var dog = new Dog();
cat.say();
dog.say();
Fiddle 这里(查看控制台输出).
Fiddle here (look at the console output).
这篇关于如何在 JavaScript 中创建抽象基类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文