我想在Javascript中创建两个函数类:Animal和Zebra。客户端脚本用于实例化Zebra,然后Zebra应该能够从Animal中查看和调用函数:
斑马:动物
因此,我尝试了以下内容,我使用jQuery $.extend()
将Animal作为Zebra的基类:
Animal = function() {
function hi_animal() {
console.log('But I am also an animal');
}
return {
hi_animal: hi_animal
}
}
Zebra = function() {
$.extend(this, Animal);
function hi_zebra() {
console.log('I am a zebra!');
hi_animal();
}
return {
hi_zebra: hi_zebra
}
}
$(document).ready(function() {
var my_zebra = new Zebra();
my_zebra.hi_zebra();
});
浏览器日志应显示以下两行:
我是斑马郎 但我也是一个动物
但是,我只看到:
我是斑马! 未捕获的ReferenceError:未定义hi_animal
这是fiddle。
我错过了什么?
答案 0 :(得分:3)
JS中的类继承语法不正确。 $.extend
旨在转置对象属性。它对函数/类的任何影响纯属巧合。
您应该定义基类,然后对派生实例进行原型设计。试试这个:
function Animal() {
// put constructor logic here...
}
Animal.prototype.hi_animal = function() {
console.log('But I am also an animal');
}
Zebra.prototype = new Animal();
Zebra.prototype.constructor = Zebra; // otherwise constructor will be Animal()
function Zebra() {
// put constructor logic here...
}
Zebra.prototype.hi_zebra = function() {
console.log('I am a zebra!');
this.hi_animal();
}
$(document).ready(function() {
var my_zebra = new Zebra();
my_zebra.hi_zebra();
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
&#13;
答案 1 :(得分:3)
function Animal() {
// put constructor logic here...
}
Animal.prototype.hi_animal = function() {
console.log('But I am also an animal');
}
function Zebra() {
// put constructor logic here...
}
Zebra.prototype.hi_zebra = function() {
console.log('I am a zebra!');
this.hi_animal();
}
Zebra.prototype.hi_animal = Animal.prototype.hi_animal;
$(document).ready(function() {
var my_zebra = new Zebra();
my_zebra.hi_zebra();
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
&#13;