这是我的抽象类:
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)
OR
Dog.prototype = Animal.prototype
我也试过了var Dog = Object.create(Animal)
这给了我一个错误。
答案 0 :(得分:0)
在Animal
内部,您可以if
检查当前constructor
是否为Animal
,如果是Dog
则抛出错误。当您在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()
。
class CompetenceGroupeType extends AbstractType
{
/**
* @param FormBuilderInterface $builder
* @param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('titre')
->add('competence_items', CollectionType::class, array(
'entry_type' => CompetenceItemType::class,
'allow_add' => true,
'allow_delete' => true,
'label' => false,
'prototype' => true,
))
//->add('save', SubmitType::class)
;
}
/**
* @param OptionsResolver $resolver
*/
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'AppBundle\Entity\CompetenceGroupe',
));
}
}