gpt4 book ai didi

带有对象创建的 Javascript 抽象类

转载 作者:行者123 更新时间:2023-12-03 11:17:01 24 4
gpt4 key购买 nike

这是我的抽象类:

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) 这给了我一个错误。

最佳答案

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()

关于带有对象创建的 Javascript 抽象类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44994426/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com