带有对象创建的Javascript抽象类
这是我的抽象类:带有对象创建的Javascript抽象类,javascript,inheritance,abstract-class,Javascript,Inheritance,Abstract Class,这是我的抽象类: var Animal = function(){ this.name = '' this.legs = 0; throw new Error("cannot instantiate abstract class"); } Animal.prototype.walk = function(){ console.log(this.name+ " walked")}; 创建新的混凝土类: var Dog = function(){} ; 现在我想制作一个具
var Animal = function(){
this.name = ''
this.legs = 0;
throw new Error("cannot instantiate abstract class");
}
Animal.prototype.walk = function(){ console.log(this.name+ " walked")};
创建新的混凝土类:
var Dog = function(){} ;
现在我想制作一个具体的类Dog来继承抽象类Animal。我在下面尝试了两种方法。哪一个是标准的
Dog.prototype = Object.create(Animal.prototype)
或
我还尝试了
var Dog=Object.create(Animal)
,这给了我一个错误 在Animal
类中,您可以进行if
检查当前的构造函数是否为Animal
,如果为,则抛出错误。当您在Dog
内部调用父构造函数并从原型继承时,还需要将其构造函数指针设置为Dog
var Animal=function(){
this.name=“”
此参数为0;
if(this.constructor==Animal){
抛出新错误(“无法实例化抽象类”);
}
}
Animal.prototype.walk=函数(){
console.log(this.name+“walked”)
};
功能狗(){
动物。叫(这个);
}
Dog.prototype=Object.create(Animal.prototype);
Dog.prototype.constructor=Dog;
var inst=新狗;
仪器名称='lorem';
inst.walk()
扩展a的标准方法是使用@str,如果您使用的是ES6,则可能是,但OP似乎没有查看@this link may help@smnbbrv有JavaScript Transpiler。那么,有没有理由不使用ES6+?ES6听起来像是一个新标准。那么,在ES6出现之前,开发人员应该做些什么呢?
Dog.prototype = Animal.prototype