我想在Javascript中创建两个功能类:动物类和斑马类。客户端脚本将实例化Zebra,然后Zebra应该能够看到并调用野兽中的函数:
斑马:动物
因此,我尝试了以下方法,其中我使用jQuery $.extend()
使动物成为斑马的一个基类:
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未定义
这是一个小提琴。
我遗漏了什么?
发布于 2016-10-03 02:15:17
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>
发布于 2016-10-03 02:32:37
@Rory McCrossan的答案完全正确。但我喜欢Javascript的一点是原型系统是如何工作的。下面是Rory的一个稍微修改过的版本,但是如果不使用prototype链,这可能有一个性能优势,因为它使原型链更加平坦。在C# / Delphi等的世界里,就像你可以操纵VMT一样。
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();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
https://stackoverflow.com/questions/39829089
复制相似问题