Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/symfony/6.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
原型上子对象的Javascript继承_Javascript_Inheritance - Fatal编程技术网

原型上子对象的Javascript继承

原型上子对象的Javascript继承,javascript,inheritance,Javascript,Inheritance,我刚刚开始学习JS中的原型继承,我希望子类对象的子对象(def2)继承自超类对象的子对象(def)。以下代码将解释我的意思: function Animal(name) { this.name = name; this.def = { FieldA: 'aaa', FieldB: 'bbb' } } function Rabbit(name, category) { Animal.apply(this, argume

我刚刚开始学习JS中的原型继承,我希望子类对象的子对象(def2)继承自超类对象的子对象(def)。以下代码将解释我的意思:

function Animal(name)
{
    this.name = name;       
    this.def = {
        FieldA: 'aaa',
        FieldB: 'bbb'
    }
}

function Rabbit(name, category)
{
    Animal.apply(this, arguments);  

    this.def2 = { };        
    this.def2.prototype = Animal.def;       
    alert(this.def2.FieldA);  // this is undefined 

}

我建议您阅读或阅读类似文章

您必须这样说。def2=新动物(名称)。如果您使用prototype,则使用“new”。我不希望def2具有来自Animal的属性/方法,而是来自Animal.def您描述的:this.def2=this.def;好的,但现在在rabbit中,我想定义另一个名为def2的对象,它应该继承Animal.def的属性。我该怎么做?Animal.def是否始终是一个对象(默认值)?然后克隆它-但不确定为什么要克隆它。我将使用$.extend()更新代码,对吗?我在考虑克隆,但由于某种原因没有走那条路是的,
jQuery.clone(this.def)
jQuery.extend({},this.def)
是你要找的,我相信
function Rabbit(name, category) {
    Animal.apply(this, arguments);
    this.def2 = clone(this.def); //where clone is a function similar to http://stackoverflow.com/questions/122102/most-efficient-way-to-clone-an-object#answer-122190   

    alert(this.def.FieldA);  // this is 'aaa'
}
Rabbit.prototype = new Animal(); //inherit Animal
Rabbit.prototype.constructor = Rabbit;