这是我的Abstract类:
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)或
Dog.prototype = Animal.prototype我还尝试了var Dog = Object.create(Animal),它给了我一个错误。
发布于 2017-07-09 17:32:27
在Animal类中,您可以让if检查当前的constructor是否为Animal,如果是,则抛出错误。当您在Dog内部调用父构造函数并从prototype继承时,您还需要将其构造函数指针设置为Dog。
var Animal = function() {
this.name = ''
this.legs = 0;
if (this.constructor == Animal) {
throw new Error("cannot instantiate abstract class");
}
}
Animal.prototype.walk = function() {
console.log(this.name + " walked")
};
function Dog() {
Animal.call(this);
}
Dog.prototype = Object.create(Animal.prototype);
Dog.prototype.constructor = Dog;
var inst = new Dog;
inst.name = 'lorem';
inst.walk()
https://stackoverflow.com/questions/44994426
复制相似问题